216. 组合总和 III

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。



    Stack<Integer> stack = new Stack<>();
    List<List<Integer>> ret = new ArrayList<>();
    public List<List<Integer>> combinationSum3(int k, int n) {

        dfs(k,n,1);
        return ret;
    }

    public void dfs(int k, int n, int index) {
        if(n<0) {
            return;
        }

        if(n==0) {
            if(k == 0) {
                ret.add(new ArrayList<>(stack));
            }
            return;
        }

        for(int i=index;i<=9;i++) {
            stack.push(i);
            // k:个数减一
            // n:和键值
            // i:索引要加一,不能重用
            dfs(k-1,n-i,i+1);
            stack.pop();
        }
    }
posted @ 2022-02-28 14:48  一颗青菜  阅读(8)  评论(0)    收藏  举报