Java implementation LeetCode 40 Total composition II (b)

40. The composition sum II

Given an array of candidates and the number one goal target, you can find all the candidates for the target numbers and combinations.

Each number candidates used only once in each combination.

Description:

All figures (including the target number) are positive integers.
Solution Set can not contain duplicate combinations thereof.
Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
the set is solved:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
example 2:

Input: candidates = [2,5,2,1,2], target = 5,
the set is solved:
[
[1,2,2],
[5]
]

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/combination-sum-ii
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

PS: is more than more than one on one with not repeat

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates);
        backtrack(candidates, 0, target, res, new ArrayList<Integer>());
        return res;
    }
    private void backtrack(int [] candidates, int start, int target, List<List<Integer>> res, ArrayList<Integer> tmp) {
        if (target == 0) {
            res.add(new ArrayList(tmp));
            return;
        }
        for (int i = start; i < candidates.length; i ++) {
            if (i > start && candidates[i] == candidates[i-1]) continue;
            if (target - candidates[i] >= 0) {
                tmp.add(candidates[i]);
                backtrack(candidates, i + 1, target - candidates[i], res, tmp);
                tmp.remove(tmp.size() - 1);
            } else {
                break;
            }
        }
    }
}
Released 1153 original articles · won praise 10000 + · views 420 000 +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104315137