-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
【Day 81 】2024-02-04 - 40 组合总数 II #85
Comments
|
悄悄回归打卡! 几周没写, 又没感觉了. 看到题, 两眼一抹黑 参考题解...😭 class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new LinkedList<>();
helper(res, list, target, candidates, 0);
return res;
}
public void helper(List<List<Integer>> res, List<Integer> list, int target, int[] candidates, int start) {
//如果target已经被消耗完, 即为一个valid combination
// test case
if (target == 0) {
res.add(new LinkedList<>(list));
return;
}
// 从start位置开始,
for (int i = start; i < candidates.length; i++) {
// target 比candidate要大, 才有可能是valid solution
if (target - candidates[i] >= 0) {
// 这里就是去重复的过程.
// 因为一直是recursion tree所以其实包含该元素的tree已经搜过了
// 不会错过1,1,1的情况是因为test case(base case)
if (i > start && candidates[i] == candidates[i - 1])
continue;
list.add(candidates[i]);
helper(res, list, target - candidates[i], candidates, i + 1);
// 删掉最后一个的原因是: recursion call每次删除一个, 恢复原状
list.remove(list.size() - 1);
}
}
}
} 时间复杂度里面有2^n 也是因为有recursion tree T(n) = T(n-k) + O(n-k). 不太确定 |
思路与39题的区别在于 candidates数组中的元素不可重复使用 观察示例1可以发现,因为candidates数组存在重复元素,所以结果集中会出现相同组合,所以还需要进行去重剪枝处理 代码class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
int length = candidates.length;
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates);
Deque<Integer> queue = new ArrayDeque<>();
dfs(candidates,0,target,length,queue,res);
return res;
}
private void dfs(int[] candidates, int begin, int target, int length, Deque<Integer> queue, List<List<Integer>> res) {
if (target==0){
res.add(new ArrayList<>(queue));
System.out.println();
return;
}
for (int i = begin; i < length; i++) {
if (target - candidates[i] < 0) {
break;
}
//同一层相同元素进行剪枝
if (i > begin && candidates[i] == candidates[i - 1]) {
continue;
}
queue.addLast(candidates[i]);
//递归元素+1
dfs(candidates, i + 1, target - candidates[i], length, queue, res);
queue.removeLast();
}
}
} |
class Solution {
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
40 组合总数 II
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/combination-sum-ii/
前置知识
题目描述
The text was updated successfully, but these errors were encountered: