LeetCode 40 Combination Sum II[數組總和 II]

題目
給定一個數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和爲 target 的組合。

candidates 中的每個數字在每個組合中只能使用一次。

說明:
所有數字(包括目標數)都是正整數。
解集不能包含重複的組合。

示例 1:

 輸入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集爲:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

示例 2:

輸入: candidates = [2,5,2,1,2], target = 5,
所求解集爲:
[
  [1,2,2],
  [5]
]

解題思路:
和39題不同之處:一,本題有重複節點;第二,每個節點只能用一次。 遞歸調用 calculate(args, i, target - args[i], temp, res)中i修改爲i+1,這樣就不會重複使用數組中的節點。
本題中有重複節點,必定會有重複的組合生成,遍歷中添加**if (i != start && args[i] == args[i-1]) { continue; }**可以避免生成重複的組合。 比如[1,1,2] 和target = 3。會有第一個1和2組合、第二個1和2組合。 便利到第二個1開始遍歷的時候continue跳出循環,避免重複組合出現

具體代碼:

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new LinkedList<>();
        Arrays.sort(candidates);
        calculate(candidates, 0, target, new ArrayList<Integer>(), res);
        return res;
    }
    
    public void calculate(int[] args, int start, int target, ArrayList<Integer> temp, List<List<Integer>> res) {
        if (target == 0) {
            res.add(temp);
            return;
        }
    
        if (target < 0) {
            return;
        }
        
        for (int i = start; i < args.length; i++) {
            if (i != start && args[i] == args[i-1]) {
                continue;
            }
            temp.add(args[i]);
            calculate(args, i + 1, target - args[i], new ArrayList<>(temp), res);
            temp.remove(temp.size() - 1);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章