码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Combination Sum2

时间:2015-04-22 11:24:37      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:

Title:

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

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

 

For example, given candidate set 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6] 

思路:DFS搜索。与Combination Sum中的不同,每次搜索的备选项是从当前index开始到数组结束的元素。不包括重复元素。

class Solution {
public:
    vector<vector<int> > results;
    vector<vector<int> > combinationSum2(vector<int> &num, int target) {

        if (num.empty() || num.size() == 0)
            return results;
        sort(num.begin(),num.end());
        vector<int> result;
        combine(num,0,target,result);
        return results;
    }

    void combine(vector<int> &num,int startIndex, int target,vector<int> &result){
        if (0 == target){
            //cout<<"add"<<endl;
            results.push_back(result);
            return ;
        }
        if (0 > target)
            return ;
        for (int i = startIndex; i < num.size(); i++){
            if (i > startIndex && num[i] == num[i-1])
                continue;
            result.push_back(num[i]);
            combine(num,i+1,target-num[i],result);
            result.pop_back();
        }
    }
};

 

LeetCode: Combination Sum2

标签:

原文地址:http://www.cnblogs.com/yxzfscg/p/4446715.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!