1. 程式人生 > 其它 >LeetCode40.組合總和II

LeetCode40.組合總和II

程式碼(樹層去重)

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    boolean[] used = new boolean[100]; // used預設值是false

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtracking(candidates, target, 0, 0);
        return res;
    }
    public void backtracking(int[] candidates, int target, int sum, int startIndex) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
        }
        for (int i = startIndex; i <= candidates.length - 1 && used[i] == false && sum + candidates[i] <= target; i ++) {
            if (i > startIndex && candidates[i] == candidates[i - 1]) continue;
            sum += candidates[i];
            path.add(candidates[i]);
            used[i] = true;
            backtracking(candidates, target, sum, i + 1);
            used[i] = false;
            path.remove(path.size() - 1);
            sum -= candidates[i];
        }
    }
}
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    //boolean[] used = new boolean[100]; // used預設值是false

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtracking(candidates, target, 0, 0);
        return res;
    }
    public void backtracking(int[] candidates, int target, int sum, int startIndex) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
        }
        for (int i = startIndex; i <= candidates.length - 1; i ++) {
            if (i > startIndex && candidates[i] == candidates[i - 1]) continue;
            if (sum + candidates[i] <= target) {
                sum += candidates[i];
                path.add(candidates[i]);
                //used[i] = true;
                backtracking(candidates, target, sum, i + 1);
                //used[i] = false;
                path.remove(path.size() - 1);
                sum -= candidates[i];
            } 
        }
    }
}

跳過同一樹層使用過的元素

if (i > startIndex && candidates[i] == candidates[i - 1]) {
    continue;
}