LeetCode39. Combination Sum

题意

给一个序列以及一个目标值, 使用序列中的数相加和为目标值, 求一共有多少种组合; 每个数可选取多次

解法

  • 递归 + 回溯 + 剪枝

代码


vector<vector<int>> ans;

void dfs(vector<int> res, int target, vector<int> candidates, int index)
{
    if (index == candidates.size()) return;
    if (target < 0) return;
    if (target == 0) {
        ans.push_back(res);
        return;
    }

    dfs(res, target, candidates, index+1);
    if (target - candidates[index] < 0) return;
    res.push_back(candidates[index]);
    dfs(res, target-candidates[index], candidates, index);
}

vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
    vector<int> res;
    dfs(res, target, candidates, 0);

    return ans;
}
posted @   Figure_at_a_Window  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示