力扣: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();
        }
    }
}
相关推荐
sin_hielo3 小时前
leetcode 1611
算法·leetcode
淮北4944 小时前
windows11配置wsl安装ubuntu20.04
windows·学习·ubuntu·wsl
来荔枝一大筐4 小时前
C++ LeetCode 力扣刷题 541. 反转字符串 II
c++·算法·leetcode
小白程序员成长日记6 小时前
2025.11.07 力扣每日一题
数据结构·算法·leetcode
·白小白6 小时前
力扣(LeetCode) ——209. 长度最小的子数组(C++)
c++·算法·leetcode
shykevin6 小时前
uni-app x开发商城系统,商品列表点击跳转至商品详情页
windows·uni-app
小白程序员成长日记7 小时前
2025.11.08 力扣每日一题
算法·leetcode·职场和发展
std860218 小时前
微软解除 Win11 限制,“毛玻璃”效果将无处不在
windows
csdn_aspnet8 小时前
如何在 Mac、Ubuntu、CentOS、Windows 上安装 MySQL 客户端
linux·windows·mysql·macos·centos
24kHT8 小时前
conda以及Jupyter notebook的使用
windows·jupyter·conda