39. Combination Sum

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 }
原文地址:https://www.cnblogs.com/hyxsolitude/p/12315463.html