Leetcode 39
阿新 • • 發佈:2020-09-09
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; } };
普通回溯題,說是剪枝,其實算是貪心吧……所以需要事先排序