力扣: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();
        }
    }
}
相关推荐
快去睡觉~7 小时前
力扣400:第N位数字
数据结构·算法·leetcode
gzzeason8 小时前
LeetCode Hot100:递归穿透值传递问题
算法·leetcode·职场和发展
qq_5139704411 小时前
力扣 hot100 Day74
数据结构·算法·leetcode
北十南13 小时前
SODA自然美颜相机(甜盐相机国际版) v9.3.0
android·windows·数码相机
nbsaas-boot13 小时前
用 FreeMarker 动态构造 SQL 实现数据透视分析
数据库·windows·sql·freemarker·数据报表
weixin_4462608514 小时前
windows下hashcat使用gpu破解execl打开密码
windows
墨染点香15 小时前
LeetCode 刷题【42. 接雨水】
算法·leetcode·职场和发展
Evaporator Core1 天前
Windows批处理脚本自动合并当前目录下由You-get下载的未合并的音视频文件
windows·音视频
এ᭄画画的北北1 天前
力扣-347.前K个高频元素
算法·leetcode
亮亮爱刷题1 天前
算法提升之树上问题-(LCA)
数据结构·算法·leetcode·深度优先