39. The combination of the sum
Given a non-repeating array element candidates and a target number target, you can find all the candidates for the target numbers and combinations thereof.
Unlimited numbers of candidates may be selected is repeated.
Description:
All figures (including the target) are positive integers.
Solution Set can not contain duplicate combinations thereof.
Example 1:
Input: candidates = [2,3,6,7], target = 7,
the set is solved:
[
[7],
[2,2,3]
]
Example 2:
Input: candidates = [2,3,5], target = 8,
the set is solved:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/combination-sum
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates);
//System.out.println(candidates);
backtrack(candidates, target, res, 0, new ArrayList<Integer>());
return res;
}
private void backtrack(int[] candidates, int target, List<List<Integer>> res, int i, ArrayList<Integer> tmp_list) {
if (target < 0) return;
if (target == 0) {
res.add(new ArrayList<>(tmp_list));
return;
}
for (int start = i; start < candidates.length; start++) {
if (target < 0) break;
//System.out.println(start);
tmp_list.add(candidates[start]);
//System.out.println(tmp_list);
backtrack(candidates, target - candidates[start], res, start, tmp_list);
tmp_list.remove(tmp_list.size() - 1);
}
}
}