Saturday, July 11, 2015

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.

For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 
Have you met this question in a real interview? 
Yes
Example
given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 

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.
public class Solution {
    /**
     * @param candidates: A list of integers
     * @param target:An integer
     * @return: A list of lists of integers
     */
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        // write your code here
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Arrays.sort(candidates);
        combinationSum(res, 0, candidates, new ArrayList<Integer>(), target);
        return res;
       
    }
    private void combinationSum(List<List<Integer>> res, int start, int[] candidates, List<Integer> sub, int target){
        if(target == 0){
            res.add(new ArrayList<Integer>(sub));
            return;
        }
       
        for(int i = start; i < candidates.length; i++){
            if(i > 0 && candidates[i] == candidates[i-1]) continue;
            if(candidates[i] <= target){
                sub.add(candidates[i]);
                combinationSum(res, i, candidates, sub, target-candidates[i]);
                sub.remove(sub.size()-1);
            }
        }
    }
}

No comments:

Post a Comment