题意
给定一个可能有重复元素的序列,找出取出的数之和为target的方案
思路
和上一题差不多,这次里面元素的个数受到了限制,所以可以统计每个数出现的次数,然后对序列进行排序去重,然后用和上一题一样的方法来求,只是中间取出元素的个数不能超过它的个数.
代码
class Solution {
public:
map<int, int>mp;
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
size_t len = candidates.size();
for(int i = 0; i < len; i++){
mp[candidates[i]]++;
}
int n = unique(candidates.begin(), candidates.end()) - candidates.begin();
vector<int>temp;
for(int i = 0; i < n; i++){
temp.push_back(candidates[i]);
}
vector<int>now;
vector<vector<int> >ans;
findAns(temp, ans, now, 0, target);
return ans;
}
private:
void findAns(vector<int>& temp, vector<vector<int> >& ans, vector<int>& now, int id, int target){
if(target == 0){
ans.push_back(now);
return ;
}
if(id >= temp.size()) return ;
for(int i = 0; i <= mp[temp[id]] && i * temp[id] <= target; i++){
for(int j = 0; j < i; j++){
now.push_back(temp[id]);
}
findAns(temp, ans, now, id + 1, target - i * temp[id]);
for(int j = 0; j < i; j++){
now.pop_back();
}
}
}
};