您的位置:首页 > 其它

Combination Sum:非重复数组中选取若干元素求和等于给定值

2017-10-06 14:03 281 查看
Given a set of candidate numbers (C) (without duplicates) 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.
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]
]


注意:给顶元素不重复,但是一个元素可以被多次选取

思路:深度优先遍历,注意同意元素可被取多次,所以递归调用时仍从当前元素下表调用,打印数组时要注意每个元素被选取次数。

class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(candidates);
dfs(candidates,0,0,target,list);
return list;

}
static int[] index = new int[10000];
public static void dfs(int[] candidates,int sum,int i,int target,List list){
if(sum>target) return;
if(sum==target){
ArrayList<Integer> l = new ArrayList();
for(int j=0;j<candidates.length;j++){
if(index[j]!=0){
for(int c = index[j];c>0;c--){
l.add(candidates[j]);
}
}
}
list.add(l);
return;
}else{
for(int j = i ;j<candidates.length;j++){
index[j]++;
dfs(candidates,sum+candidates[j],j,target,list);
index[j]--;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐