栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

力扣-39题 组合总和(C++)- 回溯+有价值

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

力扣-39题 组合总和(C++)- 回溯+有价值

题目链接:https://leetcode-cn.com/problems/combination-sum/
题目如下:

class Solution {
public:
    //深搜(搜索回溯)
    vector> ans;
    vector cur;

    vector> combinationSum(vector& candidates, int target) {

        sort(candidates.begin(),candidates.end());
        dfs(candidates,target,0);

        return ans;
    }

    //表示当前在candidates数组的第start位,还剩target要组合,已经组合的列表为ans
    void dfs(vector& candidates,int target,int start){
        if(target==0){//满足要求,则放入结果中,并返回
            ans.push_back(cur);
            return ;
        }

        for(int i=start;itarget) break;//已排序,若>target,则直接跳出此次遍历,否则,就放入当前cur中
            else cur.push_back(candidates[i]);

            dfs(candidates,target-candidates[i],i);//从当前位置重新开始dfs,因为每个数字可以重复被选取
            cur.pop_back();//此时,弹出当前cur位置,继续下一个位置
        }
    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/290373.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号