您的位置:首页 > 其它

39 Combination Sum

2015-09-04 15:45 281 查看
public class Solution {
List<List<Integer>> res = new ArrayList<List<Integer>>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if(candidates==null||candidates.length==0) return res;
Arrays.sort(candidates);
int len = candidates.length;
List<Integer> list = new ArrayList<Integer>();
dfs(list, candidates, 0, target);
return res;
}

public void dfs(List<Integer> list, int[] candidates, int sum, int target){
int len = candidates.length;
for(int i=0;i<len;++i){
if(sum + candidates[i]==target){
List<Integer> tmp = new ArrayList<Integer>(list);
tmp.add(candidates[i]);
Collections.sort(tmp);
if(!res.contains(tmp)){
res.add(tmp);
}
}else if(sum + candidates[i] < target){
List<Integer> t1 = new ArrayList<Integer>(list);
t1.add(candidates[i]);
dfs(t1, candidates, sum + candidates[i], target);
}else{
break;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: