ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

LeetCode 39 Combination Sum 回溯

2022-08-08 19:04:23  阅读:216  来源: 互联网

标签:39 target res Sum pos vector candidates combinations LeetCode


Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Solution

由于每个元素可以使用多次,所以在 \(DFS\) 的时候,起始依旧为上一次的 \(pos\);每次 \(DFS\) 的时候,如果剩余的 \(target\ge cand[i]\),那么说明这是一个可能的解,则 \(push\_back\),否则跳过,当剩余 \(target=0\) 时,加入答案

点击查看代码
class Solution {
private:
    vector<vector<int>> ans;
    vector<int> res;
    
    void dfs(vector<int> cd, int pos, vector<int>& res, int tgt){
        if(tgt==0){
            ans.push_back(res);return;
        }
        while(pos<cd.size() && tgt-cd[pos]>=0){
            res.push_back(cd[pos]);
            dfs(cd, pos, res, tgt-cd[pos]);
            pos++;
            res.pop_back();
        }
    }
    
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        dfs(candidates, 0, res, target);
        return ans;
    }
};

标签:39,target,res,Sum,pos,vector,candidates,combinations,LeetCode
来源: https://www.cnblogs.com/xinyu04/p/16563061.html

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有