leetcode日记(30)组合总和Ⅱ

一开始我低估了这题的难度,以为用贪心算法或者上一题的解法就能做出来TT后来发现很多做法会得出重复解,只能另辟蹊径了...!

想出来的解法是先将candidates中重复的元素提出来用数组记录重复的个数,然后将重复的元素去掉,接着用原来(上一题)的方法依次遍历元素,如果能取该元素就继续遍历该元素,不能取就全部跳过,最终可以得到正确解。

cpp 复制代码
class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target){
        vector<vector<int>> v;
        vector<int> vec;
        sort(candidates.begin(),candidates.end());
        vector<int> g(candidates[candidates.size()-1]+1);
        int u=0;
        for(int i=candidates.size()-1;i>=0;i--){
            while(i>=1&&candidates[i]==candidates[i-1]){
                i--;
                g[candidates[i]]++;
            }
        }
        for(int i=0;i<g.size();i++) cout<<g[i]<<" ";
        candidates.erase(unique(candidates.begin(), candidates.end()), candidates.end());
        hs(candidates,target,v,vec,candidates.size()-1,g);
        return v;
    }
    void hs(vector<int> candidates, int target,vector<vector<int>>& v,vector<int> vec,int x,vector<int> g){
        while(x>1&&candidates[x]==candidates[x-1]) x--;
        for(;x>=0;x--){
            if(candidates[x]<target){
                vec.push_back(candidates[x]);
                if(g[candidates[x]]>0){
                    g[candidates[x]]--;
                    hs(candidates,target-candidates[x],v,vec,x,g);
                    g[candidates[x]]++;
                }
                else hs(candidates,target-candidates[x],v,vec,x-1,g);
                vec.pop_back();
            }
            else if(candidates[x]==target){
                vec.push_back(candidates[x]);
                v.push_back(vec);
                vec.pop_back();
            }
        }
    }
};
相关推荐
SWAGGY..几秒前
Linux系统编程:(十三)环境变量
java·linux·算法
Black蜡笔小新10 分钟前
自动化AI算法训练服务器DLTM一体化训推平台构建企业专属AI能力中台
人工智能·算法·自动化
sjsjs1124 分钟前
力扣3558. 给边赋权值的方案数 I
算法·leetcode·职场和发展
hujinyuan2016024 分钟前
2025年12月中国电子学会青少年机器人技术等级考试试卷(四级) 真题+答案
算法·机器人
啦啦啦啦啦zzzz27 分钟前
算法总结(双指针)
c++·算法·双指针
花间相见38 分钟前
【LeetCode01】—— 无重复字符的最长子串:滑动窗口经典题详解
python·算法·leetcode
wabs66643 分钟前
关于动态规划【力扣96.不同的二叉搜索树的递推公式怎么理解?】
算法·动态规划
嵌入式ZYXC1 小时前
第8篇:《面试题:模拟地和数字地为什么要分开?怎么接?》
stm32·单片机·嵌入式硬件·面试·职场和发展
QiLinkOS1 小时前
极客与商业思维的融合实践(1)
c语言·数据库·c++·人工智能·算法·开源协议
fu的博客1 小时前
【数据结构16】图:基于邻接矩阵、邻接表实现DFS/BFS
数据结构·算法