40. Combination Sum II

原创 2016年08月31日 10:48:35

回溯,因为每个数字只能出现一次,所以当下一个数字和当前数字相同时,若当前数退出时,下一个数不需要进栈了

class Solution {
public:
    void GetRes(vector<int>& nums,int sta,vector<vector<int>>& res,int sum,vector<int> ans,int target)
    {
        if(sum==target&&ans.size()>0)
        {
            res.push_back(ans);
            return;
        }
        if(sum>target)
            return;
        for(int i=sta;i<nums.size();i++)
        {
            ans.push_back(nums[i]);
            GetRes(nums,i+1,res,sum+nums[i],ans,target);
            ans.pop_back();
            while(i+1<nums.size()&&nums[i+1]==nums[i])
                i++;
        }
    }
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int>> res;
        vector<int> ans;
        
        sort(candidates.begin(),candidates.end());
        GetRes(candidates,0,res,0,ans,target);
        return res;
    }
};



版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode_40---Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations ...

Leetcode #40. Combination Sum II 组合求和2 解题报告

1 解题思想这道题是昨天的升级版,先看看这个 Leetcode #39. Combination Sum 组合求和 解题报告这道题的改变就是每个位置的数只能用一次了,但是如果本身就给了多个的话就无...

LeetCode40 Combination Sum II 解析

详细见:leetcode.com/problems/combination-sum-ii C和Python的去重算法,应该记住。 Java是很久之前写的,并不好。 规则是:相同数字。 ...

[LeetCode-Java]40. Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in...

Leetcode 40. Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in...

[leetcode] 39& 40 Combination Sum I& II

if (i != index && num[i] == num[i - 1]) continue; Given a set of candidate numbers (C) and a target...

LeetCode(40) Combination Sum II

题目如下: My Submissions Question Solution  Given a collection of candidate numbers (C) and a target num...

LeetCode OJ-40-Combination Sum II

题目: Given a collection of candidate numbers (C) and a target number (T), find all unique combinatio...

LeetCode_OJ【40】Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in...

DAY19:leetcode #40 Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)