leetcode-39 組合總和

題目描述

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

candidates 中的數字可以無限制重複被選取。

說明:

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

題目代碼

List<List<Integer>> res=new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (candidates==null)return res;
        // 排序剪枝
        Arrays.sort(candidates);
        dfs(target,0,new Stack<Integer>(),candidates);
        return res;
    }
    //深度遍歷
    private void dfs(int target, int index, Stack<Integer> pre, int[] candidates) {
        //等於零說明結果符合要求
        if (target==0){
            res.add(new ArrayList<>(pre));
            return;
        }
        //遍歷,index爲本分支上一節點的減數的下標
        for (int i=index;i<candidates.length;i++){
            //如果減數大於目標值,則差爲負數,不符合結果
            if (candidates[i]<=target){
                pre.push(candidates[i]);
                //目標值減去元素值
                dfs(target-candidates[i],i,pre, candidates);
                //每次回溯將最後一次加入的元素刪除
                pre.pop();
            }else{
                // 剪枝
                break;
            }
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章