1. 题意
给一堆数,和一个目标和,求所有可能的不重复的组合。
组合总数
2. 题解
主要是去重,每次推入数到目标数组,将下次枚举的数的开头设为当前的下标就不会重复噜噜o_O
即如何避免 2 3 2 2\ 3\ 2 2 3 2 和 3 2 2 3\ 2\ 2 3 2 2这样的重复,这里的做法是,给定下次枚举的起始索引,
每次推入数的时候更新一下。
class Solution {
public:void gen(const vector<int> &candidates, vector<vector<int>> &ans,vector<int> &now,int csum,int target, int start){if ( csum == target ) {ans.emplace_back(now);return ;}int sz = candidates.size();for ( int i = start; i < sz; ++i ) {int v = candidates[i];if ( csum + v <= target) {now.emplace_back(v);gen( candidates, ans, now, csum + v, target, i);now.pop_back();}else {break;}}}vector<vector<int>> combinationSum(vector<int>& candidates, int target) {sort( candidates.begin(), candidates.end() );vector<vector<int>> ans;vector<int> now;gen(candidates, ans, now, 0, target, 0); return ans;}
};