LC216. 组合总和 III

 代码随想录

class Solution {

    List path = new ArrayList<>();
    List> res = new ArrayList<>();
    int sum = 0 ;

    public List> combinationSum3(int k, int n) {

        backtracking(k,n,1);

        return res;
    }   

    public void backtracking(int k,int n, int startIndex){

        if(path.size() == k && sum == n){
            res.add(new ArrayList<>(path));
            return;
        }

        for(int i = startIndex;  i <= 9 ; i ++){
            if(sum + i > n){
                break;
            }
            path.add(i);
            sum += i;

            backtracking(k,n,i+1);
            
            path.remove(path.size()-1);
            sum -= i;

        }
            
    }


}

你可能感兴趣的:(LeetCode算法题,java)