说明
题目地址:https://leetcode.com/problems/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]
]
解法
思路:对candidate数组进行排序,对candidate中的每个元素可以选择加,也可以选择不加;可以选择重复,也可以选择不重复。这里不仅要用到回溯,也要用到for循环。两个判断条件:
target == 0
则把列表添加到结果列表中,注意这个列表用clone,如果用索引list,结果会被修改掉。resultList.add(new ArrayList<>(list))
target > 0
则判断是否要加入当前元素。
package backtracking;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// https://leetcode.com/problems/combination-sum/
public class CombinationSum {
public static void main(String[] args) {
CombinationSum obj = new CombinationSum();
int[] candicates = {2, 3, 6, 7};
int target = 7;
List<List<Integer>> resultList = obj.combinationSum(candicates, target);
System.out.println(Arrays.toString(resultList.toArray()));
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> resultList = new ArrayList<>();
Arrays.sort(candidates);
recursive(candidates, target, 0, new ArrayList<>(), resultList);
return resultList;
}
public void recursive(int[] candidates, int target, int start, List<Integer> list, List<List<Integer>> resultList) {
if (target > 0) {
for (int i = start; i < candidates.length && target >= candidates[i]; i++) {
list.add(candidates[i]);
recursive(candidates, target - candidates[i], i, list, resultList);
list.remove(list.size() - 1);
}
} else if (target == 0) {
resultList.add(new ArrayList<>(list));
}
}
}