给定一个无重复元素的正整数数组 candidates 和一个正整数 target ,找出 candidates 中所有可以使数字和为目标数 target 的唯一组合。
candidates 中的数字可以无限制重复被选取。如果至少一个所选数字数量不同,则两种组合是唯一的。
对于给定的输入,保证和为 target 的唯一组合数少于 150 个。
示例 1:
输入: candidates = [2,3,6,7], target = 7
输出: [[7],[2,2,3]]
示例 2:
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
示例 3:
输入: candidates = [2], target = 1
输出: []
示例 4:
输入: candidates = [1], target = 1
输出: [[1]]
示例 5:
输入: candidates = [1], target = 2
输出: [[1,1]]
提示:
1 <= candidates.length <= 30
1 <= candidates[i] <= 200
candidate 中的每个元素都是独一无二的。
1 <= target <= 500
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
向下进行深度搜索,然后列出每一种情况进行筛选,进而
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> list = new ArrayList<>();//用于存储最终返回的答案
List<Integer> temp = new ArrayList<>(); //用于存储每一种情况下的结果。
dfs(candidates,target,list,temp,0);
return list;
}
public void dfs(int []candidates,int target,List<List<Integer>> list,List<Integer> temp,int index){
if(index == candidates.length){ //当前情况已经搜索至整个数组的末尾,即当前情况已经穷举完毕
return;
}
if(target == 0){ //从后往前逐渐递减进行搜索答案
list.add(new ArrayList<Integer>(temp)); //此处不可直接加temp,加入的为指针值,而new ArrayList<Integer>(temp)为克隆当前的链表元素
return; //当前情况已经满足即可返回
}
dfs(candidates,target,list,temp,index+1); //向深处遍历,然后到下方进行判断
if(target >= 0){ //大于0则说明当前情况下还可继续向下进行搜索
temp.add(candidates[index]);
dfs(candidates,target-candidates[index],list,temp,index); //因为自身可以无限调用所以新一轮的搜索还是从本身开始
temp.remove(temp.size()-1); //每一步的回溯过程,将状态回溯到当前状态之前的情况。
}
}
}
考虑到性能问题,要进行一定步骤的剪枝操作进行优化效率
if(target < candidates[index]){
return;
}
在此前已经进行了升序排序,因此当当前的目标值小于当前便利的值时,说明此后的每一个元素都比目标值大,可以进行剪掉,提升一定的效率。
未剪枝
剪枝后