给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
注意:解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]
提示:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
此题是经典的全排列问题,用到递归回溯的思想,但是深究还是dfs的一种把,向深处进行搜索,然后最终的时候,再将其回溯到最原始的未发生改变的状态,重点是回溯的过程。
难易程度:个人感觉难易程度还可以,但是好像全排列系列的问题的重点在于递归回溯到最初的状态,以及递归剪枝进行优化效率,还包括去重等一系列的问题,感觉挺难的从1到二,由未去重到去重。加油加油加油,相信自己。
class Solution {
int num;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> list = new ArrayList<>();
num = target;
dfs(list, candidates, 0, new ArrayList<>(), 0); //深搜的起点
return list;
}
public void dfs(List<List<Integer>> list, int[] candidates, int index, List<Integer> ans, int target) {
if (target == num) {
list.add(new ArrayList<>(ans)); //重点一定要新建链表
return;
} //找到当前路径的值
for (int i = index; i < candidates.length; i++) {
if (i > index && candidates[i] == candidates[i - 1]) {
continue;
} //在2当前路径下,保证这个位置上的数不会重复
int temp = target + candidates[i]; //当前的状态值0
if(temp <= num) {
ans.add(candidates[i]); //添加到链表中
dfs(list, candidates, i+1, ans, temp); //递归过程
ans.remove(ans.size() - 1); //恢复到最初的状态
}else {
break;
} //剪枝过程,因为数组已按非递减进行排列,所以,若当前数不符合,则其后的其他数也不可
}
}
}