xinyu04

导航

LeetCode 39 Combination Sum 回溯

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;
    }
};

posted on 2022-08-08 18:46  Blackzxy  阅读(9)  评论(0编辑  收藏  举报