leetcode-40 組合總和2

題目描述

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

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

說明:

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

題目代碼

List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if(candidates==null || candidates.length==0){
            return res;
        }
        Arrays.sort(candidates);
        dfs(target,0,new Stack<Integer>(),candidates);
        return res;
    }
    private void dfs(int tatget,int index,Stack<Integer> pre,int[] candidates){
        if(tatget == 0){
            res.add(new ArrayList<>(pre));
            return;
        }
        for(int i=index;i<candidates.length;i++){
            if(candidates[i]<=tatget){
                pre.push(candidates[i]);
                dfs(tatget-candidates[i], i+1, pre, candidates);
                pre.pop();
                // 去重
                while(i+1<candidates.length && candidates[i+1]==candidates[i]){
                    i++;
                }
            }else{
                break;
            }
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章