Leetcode 39

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef long double ld;

#define REP(x, l, u) for(ll x = l;x<u;x++)
#define RREP(x, l, u) for(ll x = l;x>=u;x--)
#define se second
#define fi first
typedef vector<int> VI;
typedef unordered_map<int,int> UMAPI;
const ll mod = 1e9 + 7;
#define len(x) x.size()

class Solution {
    VI res;
    vector<VI> ans;
    int n;
    void search(VI& candidates, int target, int start){
        if (target == 0){
            ans.emplace_back(res);
            return;
        }
        for(int i = start; i < n; i++){
            if(target  - candidates[i] >= 0){
                res.push_back(candidates[i]);
                search(candidates, target - candidates[i], i);
                res.pop_back();
            }
            else break;
        }
    }
    
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        n = len(candidates);
        sort(candidates.begin(), candidates.end());
        search(candidates, target, 0);
        return ans;
    }
};

普通回溯题,说是剪枝,其实算是贪心吧……所以需要事先排序

原文地址:https://www.cnblogs.com/KakagouLT/p/13638111.html