当前位置:网站首页>LeetCode 40:组合总和 II
LeetCode 40:组合总和 II
2022-07-07 04:27:00 【斯沃福德】
思路:回溯(元素可重不可复选)

组合问题和子集问题等价!问组合也就是问和为tartget的子集;
使用额外的sum来记录元素的和!sum记录的元素和path记录的元素相同,在递归到头后也和path一样撤回!
元素有重复则① 先排序 ②用 i>start && nums[i]==nums[i-1] 来筛选!
注意:
当sum已经超过target 就不需要遍历了, 节省开销!
class Solution {
List<List<Integer>> res=new LinkedList<>();
LinkedList<Integer> path=new LinkedList<>();
int sum=0;
public List<List<Integer>> combinationSum2(int[] nums, int target) {
//有重复要先排序 !
Arrays.sort(nums);
dfs(nums,target,0);
return res;
}
void dfs(int[] nums,int target,int start){
//终止条件1 :满足条件添加到res
if(sum==target){
res.add(new LinkedList(path));
return;
}
//终止条件2 :当sum大于target直接return,不然超出时间限制!
if(sum>target){
return;
}
for(int i=start;i<nums.length;i++){
//选择
if(i>start && nums[i]==nums[i-1]){
continue;
}
path.add(nums[i]);
sum+=nums[i];
//
dfs(nums,target,i+1);
//撤销
path.removeLast();
sum-=nums[i];
}
}
}
边栏推荐
- Pytorch parameter initialization
- Deep learning Flower Book + machine learning watermelon book electronic version I found
- 【webrtc】m98 screen和window采集
- numpy中dot函数使用与解析
- 4、 High performance go language release optimization and landing practice youth training camp notes
- After the interview, the interviewer roast in the circle of friends
- Codeforces Global Round 19
- nacos
- 242. Bipartite graph determination
- Asemi rectifier bridge rs210 parameters, rs210 specifications, rs210 package
猜你喜欢

buuctf misc USB

自定义类加载器加载网络Class

1141_ SiCp learning notes_ Functions abstracted as black boxes

After 95, the CV engineer posted the payroll and made up this. It's really fragrant

JSON introduction and JS parsing JSON

Iterable、Collection、List 的常见方法签名以及含义

Resource create package method
![[Stanford Jiwang cs144 project] lab4: tcpconnection](/img/fd/704d19287a12290f779cfc223c71c8.png)
[Stanford Jiwang cs144 project] lab4: tcpconnection

测试周期被压缩?教你9个方法去应对

nacos
随机推荐
IO stream file
1142_ SiCp learning notes_ Functions and processes created by functions_ Linear recursion and iteration
Build personal website based on flask
微信小程序中的路由跳转
解决could not find or load the Qt platform plugin “xcb“in ““.
The metauniverse of the platofarm farm continues to expand, with Dao governance as the core
JS get all date or time stamps between two time stamps
[Stanford Jiwang cs144 project] lab4: tcpconnection
[2022 actf] Web Topic recurrence
按键精灵脚本学习-关于天猫抢红包
SQL优化的魅力!从 30248s 到 0.001s
[ANSYS] learning experience of APDL finite element analysis
[UTCTF2020]file header
微信小程序中使用wx.showToast()进行界面交互
即刻报名|飞桨黑客马拉松第三期等你挑战
知识点滴 - 关于苹果认证MFI
Iterable、Collection、List 的常见方法签名以及含义
[mathematical notes] radian
Hands on deep learning (IV) -- convolutional neural network CNN
Mutual conversion between InputStream, int, shot, long and byte arrays
