Friday, February 7, 2014

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] 
Solution:
Typical dfs(depth first search) question. 
The helper method below can be used as a model to solve similar questions. 


public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> subset = new ArrayList<Integer>();
        if(target == 0 || candidates.length == 0) return result;
        Arrays.sort(candidates);
        helper(candidates, target, 0, result, subset);
        return result;
    }
    public void helper(int[] c, int target, int start, ArrayList<ArrayList<Integer>> result, ArrayList<Integer> subset){
        if(target == 0){
            result.add(new ArrayList<Integer>(subset)); // create a new copy 
            return;
        }
        if(target < 0 ) return;
        for(int i = start; i < c.length; i++){
            subset.add(c[i]);
            helper(c, target-c[i], i, result, subset);// start from i to avoid duplicate work
            subset.remove(subset.size()-1);    // remove the newly added element.
        }
    }
}

No comments:

Post a Comment