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 {
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
        int len = candidates.length;
        ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
        if(len == 0) return results;
        ArrayList<Integer> output = new ArrayList<Integer>();
        Arrays.sort(candidates);
        int sum = 0, depth = 0;
        DFS(candidates, depth, sum, target, output, results);
        return results;
    }
    
    public void DFS(int[] candidates, int depth, int sum, int target, ArrayList<Integer> output, ArrayList<ArrayList<Integer>> results ){
        if(sum > target) return;
        if(sum == target){
            ArrayList<Integer> tmp = new ArrayList<Integer>();
            tmp.addAll(output);
            results.add(tmp);
            return;
        }
        if(sum < target){
            for(int i = depth; i < candidates.length; i++){
                sum += candidates[i];
                output.add(candidates[i]);
                DFS(candidates, i, sum, target, output, results);
                output.remove(output.size()-1);
                sum -= candidates[i];
            }
        }
    }
}
原文地址:https://www.cnblogs.com/RazerLu/p/3538551.html