Friday, November 20, 2015

[leetcode] Combination Sum III

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    int k;
    public List<List<Integer>> combinationSum3(int k, int n) {
        this.k = k;
        rec(0, 1, n, new ArrayList<Integer>());
        return result;
    }
    
    private void rec(int count, int start, int target, List<Integer> fromPrev){
        if (count == k && target == 0){
            result.add(new ArrayList<Integer>(fromPrev));
        }
        if (count == k) return;
        for (int i = start; i < 10; i++){
            fromPrev.add(i);
            rec(count+1, i+1, target-i, fromPrev);
            fromPrev.remove(fromPrev.size()-1);
        }
    }
}

No comments:

Post a Comment