LeetCode Combination Sum II

本文介绍了一个使用深度优先搜索(DFS)解决组合求和问题的C++实现。该算法能够找到所有可能的组合,使得组合中的元素之和等于目标值。特别地,本文还详细解释了如何通过剪枝来避免重复解的生成。

class Solution {

public:

    vector<vector<int>> res;

    void dfs(int start,vector<int>&currentPath,vector<int> weight,int T)

    {

        if(T<0)

            return;

        if(T==0)

        {

            res.push_back(currentPath);

            return;

        }

        for(int i=start;i<=weight.size()-1;i++)

        {

            currentPath.push_back(weight[i]);

            dfs(i+1,currentPath,weight,T-weight[i]);

            currentPath.pop_back();

            while(i<weight.size()&&weight[i]==weight[i+1])  //关键一步 必须放在这里 否则会例如 17 17 重复 而且不能放在循环前面

                i++;

        }

        

        return;

    }

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {

        vector<int> a;

        sort(candidates.begin(),candidates.end());

        dfs(0,a,candidates,target);

        return res;

    }

};

去除重复的关键是: 在第一次循环中去除第一次的选择是相同数的情况
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值