首页 > 其他分享 >leet code 40. 组合总和 II

leet code 40. 组合总和 II

时间:2023-11-14 20:32:30浏览次数:27  
标签:leet code target idx int 40 -- candidates local

40. 组合总和 II

题目描述

给定一个候选人编号的集合 candidates 和一个目标数 target

找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用 一次 。

注意:解集不能包含重复的组合。

示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8

输出: [ [1,1,6], [1,2,5], [1,7], [2,6] ]

示例 2:

输入: candidates = [2,5,2,1,2], target = 5

输出: [ [1,2,2], [5] ]

提示:
● 1 <= candidates.length <= 100
● 1 <= candidates[i] <= 50
● 1 <= target <= 30

题目解析

  • 明确题目要求
  • 从一个函数重复元素的数组中,选取所有不重复的组合,使其和等于 target
  • 以数组 [1, 2, 2, 2, 5] 为例,选取和为 5 的组合
  • 现在我们开始选取元素
  • 选择 idx = 0 --> [1]
  • 选择 idx = 1 --> [1, 2]
  • 选择 idx = 2 --> [1, 2, 2] 符合要求,添加到结果集中
  • 新一轮选择
  • 选择 idx = 0 --> [1]
  • 选择 idx = 1 --> [1, 2]
  • 选择 idx = 2, val = 2 重复元素,跳过
  • 选择 idx = 3, val = 2 重复元素,跳过
  • 选择 idx = 4, --> [1, 2, 5] 不符合要求
  • 所以,我们要考虑如何在代码中去除重复元素的情况
  • 也就是,重复元素的取值方案仅执行1次
  • 如下代码
for(int i = 0;i < ...;i++) {
    if(i > 0 && xxx[i] == xxx[i - 1]) {
        continue;
    }
}

show code

class Solution {
    private List<List<Integer>> ans;

    private int[] candidates;

    private int target;

    // 追踪路径上的和.
    private int trackSum;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        // 初始化结果集合
        ans = new ArrayList<>();
        // 赋值全局变量
        this.candidates = candidates;
        this.target = target;

        // 数组排序
        Arrays.sort(candidates);

        //  0     : 表示遍历到的当前元素的数组索引下标
        //  local : 表示把路径上的元素添加到  local 中
        List<Integer> local = new ArrayList<>();
        dfs(0, local);

        return ans;
    }

    private void dfs(int idx, List<Integer> local) {
        if(target == trackSum) {
            // 符合要求,添加到结果集合中
            ans.add(new ArrayList<>(local));
            return;
        }
        if(target < trackSum) {
            // 大于目标值,直接返回
            return;
        }
        for(int i = idx;i < candidates.length;i++) {
            // 值相同的树枝,只遍历一条
            if(i > idx && candidates[i] == candidates[i - 1]) {
                continue;
            }
            local.add(candidates[i]);
            trackSum += candidates[i];

            dfs(i + 1, local);

            local.remove(local.size() - 1);
            trackSum -= candidates[i];
        }
    }
}

标签:leet,code,target,idx,int,40,--,candidates,local
From: https://blog.51cto.com/u_16079703/8378055

相关文章

  • Codeforces Round 907 (Div. 2)
    \(A.SortingwithTwos\)https://codeforces.com/contest/1891/submission/232689614\(B.DejaVu\)https://codeforces.com/contest/1891/submission/232690141\(C.SmiloandMonsters\)https://codeforces.com/contest/1891/submission/232691988\(D.Suspic......
  • 从0开始构建WSL工作平台(VSCode、ssh、Xftp、Docker)
    一、命令行界面安装1、win+S,搜索PowerShell,右键管理员身份运行2、输入命令,启用 适用于Linux的Windows子系统 功能dism.exe/online/enable-feature/featurename:Microsoft-Windows-Subsystem-Linux/all/norestart3、在MicrosoftStore中下载中意的Linux分发版(如Ubu......
  • UNet pytorch模型转ONNX模型完整code
    1importos2importtorch3importnumpyasnp4fromUnetimportUNET5os.environ["CUDA_VISIBLE_DEVICE"]=""67defmain():8demo=Demo(model_path="/xxx.pth.tar",output="pathto/xxx.onnx")9......
  • TS4000软磁直流测试系统全自动测量软件
    软磁直流测试系统全自动测量软件l 软件能够运行于Windows系统下作界面全中文提示,操作直观简捷。l 全自动控制与计算,智能化判断,最大限度消除人工操作所带来的误差。l 自动测量:Bm、Br、Hc、μi、μm 等静态磁特性参数;并绘制磁滞回线、基本磁化曲线、μ-H磁导率曲线等l 软......
  • Python字符的编码encode和解码decode
    相关阅读:字符集(CharacterSet)和编码(Encoding)的历史演化 Python字符的编码encode和解码decode进行编码str.encode("编码") 进行解码bytes.decode("编码")  s="周杰伦"bs1=s.encode("gbk")#b'xxxx'bytes类型bs2=s.encode("utf-8"......
  • Codeforces Round 809 (Div. 2) D1. Chopping Carrots (Easy Version) 题解
    题意CodeforcesRound809(Div.2)D1.ChoppingCarrots(EasyVersion)给两个整数\(n,k\),一个数组\(a\),要求构造一个同样长度的数组\(p\),使得\(\max\limits_{1\lei\len}\left(\left\lfloor\frac{a_i}{p_i}\right\rfloor\right)-\min\limits_{1\lei\l......
  • Codeforces Round 906 (Div. 2)
    A.简单题B.简单题C.比赛时没做出来,赶着回宿舍,过了几天来补发现很简单秒掉D.Doremy'sConnectingPlan给定n个结点的图,每个点有一个权值a[i],开始时图上没有边,如果与点i相邻的点(包括点i)的权值的和记为Sum_i.给定一个常数c,如果Sum_i+Sum_j>=ijc,则可以在i和j上......
  • vscode下载慢
    官网下载链接https://az764295.vo.msecnd.net/stable/6c3e3dba23e8fadc360aed75ce363ba185c49794/VSCodeUserSetup-x64-1.81.1.exe1.81.1版本镜像源的下载链接https://vscode.cdn.azure.cn/stable/6c3e3dba23e8fadc360aed75ce363ba185c49794/VSCodeUserSetup-x64-1.81.1.ex......
  • 浅谈JVM Instruction Set (Opcode)
    浅谈JVMInstructionSet(Opcode)1.背景日常开发中,遇到一个潜藏bug的java代码,借此简单回顾一下JVMInstructionSet(Opcode)知识。问题demo代码如下:publicclassBugDemo{publicstaticvoidmain(String[]args){//模拟用户输入(具有不可预测性),假设......
  • Xcode 展示failed to prepare the device for development
    首先打开链接找到https://gitee.com/Han0/iOSDeviceSupport 找到对应版本,解压其次打开终端输入 open/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport然后将解压后的文件夹放进去,即可重启xcode......