力扣: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();
        }
    }
}
相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
元亓亓亓2 天前
LeetCode热题100--105. 从前序与中序遍历序列构造二叉树--中等
算法·leetcode·职场和发展
路由侠内网穿透2 天前
本地部署 GPS 跟踪系统 Traccar 并实现外部访问
运维·服务器·网络·windows·tcp/ip
仙俊红2 天前
LeetCode每日一题,20250914
算法·leetcode·职场和发展
研华嵌入式3 天前
如何在高通跃龙QCS6490 Arm架构上使用Windows 11 IoT企业版?
arm开发·windows·嵌入式硬件
带娃的IT创业者3 天前
Windows 平台上基于 MCP 构建“文心一言+彩云天气”服务实战
人工智能·windows·文心一言·mcp
csdn_aspnet3 天前
Windows Node.js 安装及环境配置详细教程
windows·node.js
_不会dp不改名_3 天前
leetcode_21 合并两个有序链表
算法·leetcode·链表
吃着火锅x唱着歌3 天前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun3 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划