Tuesday, April 12, 2016

[LeetCode] 39. Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3] 
public class Solution {
    
    private void combinationSumAux(int[] candidates, int target, int i, int sum, List path, List> res){
               
        // Error: because of your recursive call structure, (Leave the result
        // judgement in new recursive call) result judgement has to come before boarder i == candicates.length
        if(sum == target){
            res.add(new ArrayList(path)); 
            return;
        }
       
        if(i == candidates.length)
            return; 
            
        if(sum > target)
            return;
        
        int n = candidates[i];
        
        combinationSumAux(candidates, target, i+1, sum, path, res);
                
        int count = 0;
        
        while(sum < target){
            sum += n;
            path.add(n);
            ++count;
            combinationSumAux(candidates, target, i+1, sum, path, res);
        }
        
        while(count-- > 0){
            sum -= n;
            path.remove(path.size()-1);
        }
        
        return;
        
    }
    
    public List> combinationSum(int[] candidates, int target) {
        int len = candidates.length;
        
        List> ret = new ArrayList>();
        
        if(0 == len)
            return ret;
            
        Arrays.sort(candidates);
            
        List path = new ArrayList();
            
        combinationSumAux(candidates, target, 0, 0, path, ret);
        
        return ret;
    }
}

No comments:

Post a Comment