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

39. Combination Sum

时间:2020-02-16 01:35:33      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:==   nta   temp   ++   repeat   ati   bin   date   can   

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     
 3     public void dfs(List<List<Integer>> ans, int []candidates, int pos, int target, ArrayList<Integer> temp) {
 4         if (target == 0) {
 5             
 6             
 7             ans.add(new ArrayList<>(temp));
 8            
 9             return;
10         }
11         if (target < candidates[pos]) {
12             return;
13         }
14         int n = candidates.length;
15         System.out.println(pos);
16         for (int i = pos; i < n && candidates[i] <= target; ++i) {
17             temp.add(candidates[i]);
18             dfs(ans, candidates, i, target - candidates[i],  temp);
19             temp.remove(temp.size() - 1);
20         }
21     }
22     public List<List<Integer>> combinationSum(int[] candidates, int target) {
23         Arrays.sort(candidates);
24         List<List<Integer>> ans = new ArrayList<>();
25         if (candidates.length == 0) return ans;
26         int n = candidates.length;
27         ArrayList<Integer> temp = new ArrayList<>();
28         dfs(ans, candidates, 0, target, temp);
29         return ans;
30     }
31 }

 

39. Combination Sum

标签:==   nta   temp   ++   repeat   ati   bin   date   can   

原文地址:https://www.cnblogs.com/hyxsolitude/p/12315463.html

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