题目
给定一个无重复元素的正整数数组 candidates 和一个正整数 target ,找出 candidates 中所有可以使数字和为目标数 target 的唯一组合。
candidates 中的数字可以无限制重复被选取。如果至少一个所选数字数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的唯一组合数少于 150 个。
示例
输入: candidates = [2,3,6,7], target = 7
输出: [[7],[2,2,3]]
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
输入: candidates = [2], target = 1
输出: []
输入: candidates = [1], target = 1
输出: [[1]]
输入: candidates = [1], target = 2
输出: [[1,1]]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/Ygoe9J
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:回溯
Java实现
class Solution {
List<List<Integer>> res = new ArrayList<>();
int sum = 0;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
LinkedList<Integer> track = new LinkedList<>();
track_back(candidates, track, target, 0);
return res;
}
public void track_back(int[] candidates, LinkedList<Integer> track, int target, int start) {
if (sum == target) {
res.add(new ArrayList<>(track));
return;
} else if (sum > target) return;
for (int i = start; i < candidates.length; i++) {
sum += candidates[i];
track.add(candidates[i]);
track_back(candidates, track, target, i);
sum -= candidates[i];
track.removeLast();
}
}
}