LeetCode 39. 组合总和

题目描述

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例

示例 1:

复制代码
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

示例 2:

复制代码
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:

复制代码
输入: candidates = [2], target = 1
输出: []

解法

1.选与不选

解题思路

题目中提到元素无限制重复被选取,同时又有选与不选的性质,设置两个终止条件,遍历过程中分成选与不选,当前元素如果是"选"",那么i不再加1,以此实现无限制重复被选取。

cpp 复制代码
class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector <vector <int>> ans;
        vector <int> nums;
        auto dfs = [&](this auto && dfs,int i,int sum){
            if(sum == 0){
                ans.push_back(nums);
                return;
            }

            if(i == candidates.size() || sum < 0) return;
            //不选
            dfs(i + 1,sum);
            //选
            nums.push_back(candidates[i]);
            dfs(i,sum - candidates[i]);   //i不变,实现重复选择
            nums.pop_back(); //回溯
        };
        dfs(0,target);
        return ans; 
    }
};

2.选与不选(剪枝)

上面方法中,只有递归到最后才能终止,递归过程会浪费多余时间,如果candidates是递增的,我们就只需要判断当前的sum是否小于candidates当前元素就可以确定要不要继续遍历,实现剪枝,但是给数组排序会占用额外的时间。

cpp 复制代码
class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(),candidates.end());
        vector <vector <int>> ans;
        vector <int> nums;
        auto dfs = [&](this auto && dfs,int i,int sum){
            if(sum == 0){
                ans.push_back(nums);
                return;
            }

            if(i == candidates.size() || sum < candidates[i]) return;
            dfs(i + 1,sum);
            nums.push_back(candidates[i]);
            dfs(i,sum - candidates[i]);
            nums.pop_back();
        };
        dfs(0,target);
        return ans; 
    }
};
相关推荐
数据皮皮侠AI16 小时前
顶刊同款!中国地级市风灾风险与损失数据集(2000-2022)|灾害 / 环境 / 经济研究必备
大数据·人工智能·笔记·能源·1024程序员节
Fab1an2 天前
Busqueda——Hack The Box 靶机
linux·服务器·学习·1024程序员节
技术专家2 天前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
学传打活5 天前
古代汉语是源,现代汉语是流,源与流一脉相承。
微信公众平台·1024程序员节·汉字·中华文化
学传打活10 天前
【边打字.边学昆仑正义文化】_19_星际生命的生存状况(1)
微信公众平台·1024程序员节·汉字·昆仑正义文化
unable code17 天前
[HNCTF 2022 WEEK2]ez_ssrf
网络安全·web·ctf·1024程序员节
unable code18 天前
[NISACTF 2022]easyssrf
网络安全·web·ctf·1024程序员节
unable code19 天前
BUUCTF-[第二章 web进阶]SSRF Training
网络安全·web·ctf·1024程序员节
开开心心就好20 天前
进程启动瞬间暂停工具,适合调试多开
linux·运维·安全·pdf·智能音箱·智能手表·1024程序员节
仰泳之鹅21 天前
【51单片机】第一课:单片机简介与软件安装
单片机·嵌入式硬件·51单片机·1024程序员节