码迷,mamicode.com
首页 > 其他好文 > 详细

39. Combination Sum(回溯)

时间:2018-04-21 19:46:36      阅读:421      评论:0      收藏:0      [点我收藏+]

标签:sam   limited   XA   uniq   contain   example   ted   class   rip   

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

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]
]

 

 1 class Solution {
 2     private List<List<Integer>> res = new ArrayList<>();
 3     public List<List<Integer>> combinationSum(int[] candidates, int target) {
 4         List<Integer> temp = new ArrayList<Integer>();
 5         help(temp,candidates,0,0,target);
 6         return res;
 7     }
 8     private void help(List<Integer> temp,int[] nums,int index,int cursum,int target){
 9         if(cursum>target)
10             return;
11         if(cursum==target)
12             res.add(new ArrayList<Integer>(temp));
13         for(int i = index;i<nums.length;i++){
14             temp.add(nums[i]);
15             help(temp,nums,i,cursum+nums[i],target);
16             temp.remove(temp.size()-1);
17         }
18     }
19 }

 

39. Combination Sum(回溯)

标签:sam   limited   XA   uniq   contain   example   ted   class   rip   

原文地址:https://www.cnblogs.com/zle1992/p/8902391.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!