力扣:40. 组合总和 II

回溯:

1.先声明好大集合和小集合,在调用回溯函数,终止条件为sum==target,要进行剪枝操作减少遍历的次数,去重操作防止数组中有两个相同的值来组成的集合相同。

java 复制代码
class Solution {
    List<List<Integer>> li1=new ArrayList<List<Integer>>();
    List<Integer> li2=new ArrayList<Integer>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        //接收计算总和
        int sum=0;
        //方便去重操作
        Arrays.sort(candidates);
        huisu(candidates,target,0,sum);
        return li1;
    }
    public void huisu(int[] candidates,int target,int Index,int sum){
        //终止条件
        if(sum==target ){
            li1.add(new ArrayList<>(li2));
            return ;
        }
        //遍历和剪枝操作
        for(int i=Index;i<candidates.length&&sum+candidates[i]<=target;i++){
    //去重操作
            if (i>Index&&candidates[i]==candidates[i-1]){
                 continue;
            } 
            //加入集合li2中
            li2.add(candidates[i]);
            sum+=candidates[i];
            //嵌套
            huisu(candidates,target,i+1,sum);
            //回溯操作
            sum-=li2.get(li2.size()-1);
            li2.removeLast();
        }
    }
}
相关推荐
ITHAOGE1519 小时前
下载 | Win10 2021纯净精简版,预装应用极少!(9月更新、Win10 IoT LTSC 2021版、适合老电脑)
windows·科技·物联网·微软·电脑
Vex2une1 天前
Windows 任务管理器发展史:从 80KB 救急工具到系统级监控平台
windows·进程管理·性能监控·任务管理器·winui·cpu使用率·taskmgr
Vex2une1 天前
Windows 12 新功能展望:AI 深度融合、全新界面与下一代生产力体验
人工智能·windows·copilot·winui·新功能·ai pc
0+1111 天前
算法 --模拟
c++·算法·leetcode
LRL_1 天前
【实战指南】Node.js 跨平台依赖下载:如何在 Windows/Linux 环境下互跨下载目标系统的 npm/pnpm 包
linux·windows·node.js
言乐61 天前
Python文字审核模型
开发语言·windows·python·django·pygame
Nil2081 天前
leetcode 739每日温度
算法·leetcode·职场和发展
xqqxqxxq1 天前
LeetCode Hot100 矩阵专题题解笔记
笔记·leetcode·矩阵
All for pursuit.1 天前
【贪心-4】581.最短无序连续子数组
数据结构·c++·算法·leetcode
释厄6231 天前
01AB 基本元理——任何智能体的三元法理·0=1→0≠1法理跃迁为天理
人工智能·windows·算法·microsoft·机器学习