BiruLyu
6/15/2017 - 12:36 AM

216. Combination Sum III.java

public class Solution {
    public void backtracking(int[] candidates, int n, int start, int k, List<Integer> temp, List<List<Integer>> res){
        if(n == 0 && k == 0){
            res.add(new ArrayList(temp));
            return;
        }
        else if( k == 0) return;
        for(int i = start; i < 10 - k; i++){
            if(n < candidates[i]) return;
            temp.add(candidates[i]);
            backtracking(candidates, n - candidates[i], i + 1, k - 1, temp, res );
            temp.remove(temp.size()-1);
        }
    }
    public List<List<Integer>> combinationSum3(int k, int n) {
        int[] candidates = {1,2,3,4,5,6,7,8,9};
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        backtracking(candidates, n, 0, k, new ArrayList<Integer>(), res);
        return res;
    }
}