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
A solution set is:
代码如下:
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);
}
}
}
}
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);
}
}
}
}
相关文章推荐
- Combination Sum
- LeetCode: Combination Sum
- LeetCode-Combination Sum
- Combination Sum
- Leetcode: Combination Sum
- LeetCode | Combination Sum
- LeetCode OJ - Combination Sum
- 【leetcode刷题笔记】Combination Sum
- leetcode之Combination Sum
- L1:Combination Sum
- Combination Sum
- LEETCODE: Combination Sum
- Combination Sum -- leetcode
- Leetcode: Combination Sum
- [LeetCode] Combination Sum 回溯
- 【leetcode】Combination Sum I && III
- leetcode 39: Combination Sum
- Combination Sum
- LeetCode题解——Combination Sum
- [leetcode]Combination Sum