Friday, March 1, 2013

[LeetCode] Combination Sum



Thought:
Recursion.  
We check whether each value could be add into the cache, if not track back, if yes, add the cache into the result.

Code:
public class Solution {
    public static ArrayList<ArrayList<Integer>> result;
    public static ArrayList<Integer> cache;
    public ArrayList<ArrayList<Integer>> combinationSum(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(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);
                    cache.remove(cache.size() - 1);
                }
            }        
        }
    }
}


No comments:

Post a Comment