(LeetCode C++)组合总和

(LeetCode C++)组合总和,第1张

给你一个 无重复元素 的整数数组 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 <= candidates.length <= 30
1 <= candidates[i] <= 200
candidate 中的每个元素都 互不相同
1 <= target <= 500

Method:

使用回溯算法向下进行遍历查找

Code:

class Solution{
public:
    void Recall(vector candidates,int index,int target,vector &temp,vector> &result){
        // 如果当前回溯深度等于n,即已经查找到数组最后一个数
        if(index == candidates.size()){
            // 回溯结束
            return;
        }
        // 如果已经得到目标数值
        if(target == 0){
            // 记录当前组合
            result.emplace_back(temp);
            // 返回上一级回溯
            return;
        }
        // 继续回溯查找
        // 跳过当前值,直接回溯下一个数字
        Recall(candidates,index + 1,target,temp,result);
        // 选择当前值进行回溯,即:candidates[index]
        // 如果当前数字组合不能满足要求
        if(target-candidates[index] >= 0){
            // 增加数字进行回溯查找
            // 记录当前数字
            temp.push_back(candidates[index]);
            // 继续回溯,目标为target-candidates[index]
            // 由于每个数字可以被无限制重复选取,因此搜索的下标仍为temp而不是temp+1
            Recall(candidates,index,target-candidates[index],temp,result);
            // 如果向后回溯过程中凑成功达到目标值,则将temp中的结果记录到result中
            // 但是如果回溯中没有找到可以实现目标的解,说明当前candidates[index]不适合
            // 此时需要需要恢复temp,pop candidates[index]
            temp.pop_back();
        }
    }
    // 对于组合数很大的问题,使用回溯法(深度优先搜索)来搜索可行解
    vector> combinationSum(vector &candidates,int target){
        // 缓存每一次的解
        vector temp;
        // 记录所有结果
        vector> result;
        //从数组第0个元素开始回溯查找,每次找到的解保存在temp,所有的解保存在result
        Recall(candidates,0, target,temp,result);
        return result;
    }
};

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/combination-sum

Reference:

【Leetcode HOT100】组合总和 c++_minus haha的博客-CSDN博客

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/2991233.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-23
下一篇 2022-09-23

发表评论

登录后才能评论

评论列表(0条)

保存