The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
- Example 1:
- Input: candidates = [2,3,6,7], target = 7,
- A solution set is:
- [
- [7],
- [2,2,3]
- ]
- Example 2:
- Input: candidates = [2,3,5], target = 8,
- A solution set is:
- [
- [2,2,2,2],
- [2,3,3],
- [3,5]
- ]
- class Solution {
- private List<List<Integer>> res = new ArrayList<>();
- public List<List<Integer>> combinationSum(int[] candidates, int target) {
- List<Integer> temp = new ArrayList<Integer>();
- help(temp,candidates,0,0,target);
- return res;
- }
- private void help(List<Integer> temp,int[] nums,int index,int cursum,int target){
- if(cursum>target)
- return;
- if(cursum==target)
- res.add(new ArrayList<Integer>(temp));
- for(int i = index;i<nums.length;i++){
- temp.add(nums[i]);
- help(temp,nums,i,cursum+nums[i],target);
- temp.remove(temp.size()-1);
- }
- }
- }
来源: http://www.bubuko.com/infodetail-2570173.html