leetcode216_组合总和III

class Solution {
    private List<List<Integer>> ans = new ArrayList();
    private List<Integer> list = new ArrayList();

    private void backtracking(int k, int n, int startIdx, int sum) {
        if(list.size() == k) {
            if(sum == 0) ans.add(new ArrayList<>(list));
            return;
        }
        for(int i = startIdx + 1; i <= sum && i < 10; i++) {
            if(sum -i >= 0) {
                sum -= i;
                list.add(i);
                backtracking(k, n, i,  sum);
                list.remove(list.size() -1);
                sum += i;
            }
        }
    }
    public List<List<Integer>> combinationSum3(int k, int n) {
        int sum = n;
        backtracking(k, n, 0, sum);
        return ans;
    }
}
posted @ 2022-04-20 08:32  明卿册  阅读(17)  评论(0编辑  收藏  举报