您的位置:首页 > 其它

Combination Sum

2017-06-04 15:01 141 查看
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]
]


代码如下:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CombinationSum {

public List<ArrayList<Integer>> combinationSum(int[] nums,int target){

List<ArrayList<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
backtrack(list,new ArrayList<>(),nums,target,0);
return list;

}

private void backtrack(List<ArrayList<Integer>> list, ArrayList<Integer> arrayList, int[] nums, int target, int start) {

if(target<0)
return;
else if(target == 0)
list.add(new ArrayList<>(arrayList));
else{
for(int i=start;i<nums.length;i++){
arrayList.add(nums[i]);
backtrack(list,arrayList,nums,target-nums[i],i);//不是i+1,因为我们可以重用相同的元素
arrayList.remove(arrayList.size()-1);
}
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息