2014年4月12日 星期六

[LeetCode] Combination Sum

Problem:
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: O(n^2)
public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
        ArrayList<Integer> list = new ArrayList<Integer>();
        getlist(candidates,target,list,ret,0);
        return ret;
    } 
    
    public void getlist(int[] candidates, int target, ArrayList<Integer> list,
    ArrayList<ArrayList<Integer>> ret,int start){
        if(target == 0){
            ArrayList<Integer> t = new ArrayList<Integer>(list);
            if(!ret.contains(t))
                ret.add(t);
            return;
        }
        
        for(int i=start; i<candidates.length; i++){
            if(target-candidates[i]>=0){
                list.add(candidates[i]);
                getlist(candidates,target-candidates[i],list,ret,i);
                list.remove(list.size()-1);                
            }else
                break;
        }
    }
}
Key concept: Like stack, need to remove last after testing a candidate

沒有留言:

張貼留言