2015年4月2日星期四

combination sum leetcode

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] 

使用dfs 因为[2,2,3]和[3,2,2]是相同的解 所以选取每次从i开始便利
这道题的重点是从哪里跳出 以及带入dfs时候的参数 , 每次取一个数之后让target 从T 变成T-C[i]
选取当T==0 时候跳出并添加到result , T<0时候跳出
每次带入result到dfs 但是千万不要在外部更改result值之后带入 


public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> tem = new ArrayList<Integer>();
        if (candidates.length == 0){
            return result;
        }
        Arrays.sort(candidates);
        dfs(result, tem, candidates, target, 0);
        return result;
    }
    public void dfs(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> tem, int[] candidates, int target, int pos){
        if (target == 0){
            result.add(new ArrayList<Integer>(tem));
            return;
        }
        if (target < 0){
            return;
        }
        for (int i = pos; i < candidates.length; i++){
            tem.add(candidates[i]);
            dfs(result, tem, candidates, target - candidates[i], i);//不传i+1 是因为选取数字可以重复,如果传i+1就跳过当前的数字了
            tem.remove(tem.size() - 1);
        }
    }
}

没有评论:

发表评论