LeetCode 40. Combination Sum II

题意

给定一个可能有重复元素的序列,找出取出的数之和为 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();
            }
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值