Friday, March 1, 2013

[LeetCode] Combination Sum II

Thought:
Basically the same with Combination Sum, but if we add some value in to the cache, we should skip the same value when we continue.

Code:
public class Solution {
    public static ArrayList<ArrayList<Integer>> result;
    public static ArrayList<Integer> cache;

    public ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates, int target) {
        result = new ArrayList<ArrayList<Integer>>();
        cache = new ArrayList<Integer>();
        Arrays.sort(candidates);
        helper(candidates, target, 0);
        return result;
    }

    public void helper(int[] candidates, int target, int index) {
        if(target == 0) {
            result.add(new ArrayList<Integer>(cache));
        }else if(index == candidates.length || candidates[index] > target) {
            return;
        }else{
            for(int i = index; i < candidates.length; i++) {
                if(candidates[i] <= target) {
                    cache.add(candidates[i]);
                    helper(candidates, target - candidates[i], i + 1);
                    cache.remove(cache.size() - 1);
                    while(i < candidates.length - 1 && candidates[i + 1] == candidates[i]) i++;
                }
            }
        }
    }
}

No comments:

Post a Comment