2014年5月11日星期日

Recursive Loop Solution - Combination Sum - DFS

DFS solution, with set was used to avoid duplicates.

public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
       
        if(candidates == null || candidates.length == 0){
            return new ArrayList<ArrayList<Integer>>();
        }
        Arrays.sort(candidates);
        return translate(combinationSumOps(candidates, target));
    }
   
    private ArrayList<ArrayList<Integer>> translate(HashSet<ArrayList<Integer>> inputs){
        ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
        Iterator it = inputs.iterator();
        while(it.hasNext()){
            results.add((ArrayList<Integer>) it.next());
        }
        return results;
    }
   
    private HashSet<ArrayList<Integer>> combinationSumOps(int[] candidates, int target){
        HashSet<ArrayList<Integer>> results = new HashSet<ArrayList<Integer>>();
       
        if(target < candidates[0]){
            return results;
        }
       
        if(Arrays.binarySearch(candidates, target) > -1){
            ArrayList<Integer> result = new ArrayList<Integer>();
            result.add(target);
            results.add(result);
        }
       
        int index = 0;
        while(index < candidates.length && target >= candidates[index]){
            int curT = target - candidates[index];
            HashSet<ArrayList<Integer>> preResults = combinationSumOps(candidates, curT);
            Iterator it = preResults.iterator();
            while(it.hasNext()){
                ArrayList<Integer> result = (ArrayList<Integer>) it.next();
                result.add(candidates[index]);
                Collections.sort(result);
                results.add(result);
            }
            index++;
        }
        return results;
    }
}

没有评论: