力扣: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();
        }
    }
}
相关推荐
呉師傅5 小时前
【使用技巧】Adobe Photoshop 2024调整缩放与布局125%后出现点菜单项漂移问题的简单处理
运维·服务器·windows·adobe·电脑·photoshop
梦帮科技6 小时前
OpenClaw 桥接调用 Windows MCP:打造你的 AI 桌面自动化助手
人工智能·windows·自动化
春日见8 小时前
如何创建一个PR
运维·开发语言·windows·git·docker·容器
C++ 老炮儿的技术栈8 小时前
VS2015 + Qt 实现图形化Hello World(详细步骤)
c语言·开发语言·c++·windows·qt
YuTaoShao8 小时前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法一)排序+滑动窗口
算法·leetcode·排序算法
浩浩测试一下9 小时前
内网---> WriteOwner权限滥用
网络·汇编·windows·安全·microsoft·系统安全
一个人旅程~9 小时前
Dell n4020双系统分区步骤和linux优化操作
linux·windows·电脑
love530love10 小时前
【高阶编译】Windows 环境下强制编译 Flash Attention:绕过 CUDA 版本不匹配高阶指南
人工智能·windows·python·flash_attn·flash-attn·flash-attention·定制编译
勾股导航10 小时前
Windows安装GPU环境
人工智能·windows·gnu
x***r15110 小时前
PhpStudy2018怎么用?完整安装与使用指南(新手必看)
windows