Thought:
Basically the same with Combination Sum II, when our cache is full, we add it to result.
Code:
public class Solution {
public static ArrayList<ArrayList<Integer>> result;
public static ArrayList<Integer> cache;
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
result = new ArrayList<ArrayList<Integer>>();
cache = new ArrayList<Integer>();
helper(n, k, 0);
return result;
}
public void helper(int candidates, int target, int index) {
if(cache.size() == target) {
result.add(new ArrayList<Integer>(cache));
}else{
for(int i = index; i < candidates; i++) {
cache.add(i + 1);
helper(candidates, target, i + 1);
cache.remove(cache.size() - 1);
}
}
}
}
No comments:
Post a Comment