leetcode_216_组合总和 III@@dfs

在这里插入图片描述

class Solution {

int tempSum;
List<List<Integer>> list=new ArrayList<>();
List<Integer> tempList=new ArrayList<>();

    public List<List<Integer>> combinationSum3(int k, int n) {
        dfs(0,1,n,k);
        return list;
    }

public void dfs(int idx,int begin,int sum,int len){
    if(idx==len){
        if(tempSum==sum){
            list.add(new ArrayList<>(tempList));
        }
        return ;
    }
    for(int i=begin;i<=9;i++){
        if(i>=sum) break;
        tempSum+=i;
        tempList.add(i);
        dfs(idx+1,i+1,sum,len);
         tempSum-=i;
        tempList.remove(tempList.size()-1);
    }
}
}

猜你喜欢

转载自blog.csdn.net/ruochen82155551/article/details/107636141