LeetCode--40--組合總和 II

題目描述:
給定一個數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和爲 target 的組合。
candidates 中的每個數字在每個組合中只能使用一次。
輸入:
candidates = [10,1,2,7,6,1,5], target = 8
candidates = [2,5,2,1,2], target = 5
輸出:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
[
[1,2,2],
[5]
]
題意:
題目描述
題解
排個序,然後相鄰判斷一下就直接dfs
代碼:

class Solution {
    public List<List<Integer>> result = new LinkedList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if(candidates.length == 0){
            return result;
        }
        Arrays.sort(candidates);
        comSum2(candidates,target,0,new LinkedList<Integer>());
        return result;

    }
    public void comSum2(int[] candidates, int target, int index, LinkedList<Integer> trace){
        if(target == 0){
            result.add(new LinkedList(trace));
            return ;
        }
        if(target > 0){
            for(int i = index; i<candidates.length; i++){
                if(i > index && candidates[i] == candidates[i - 1]) continue;
                trace.add(candidates[i]);
                comSum2(candidates,target - candidates[i],i+1,trace);
                trace.removeLast();
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章