Combination Sum II

来源:互联网 发布:php 接口验证 编辑:程序博客网 时间:2024/06/16 00:21

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 (a1a2, … , 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] 

解题思路:

和combination sum i相似的计算,不过candidates中的元素不能重复使用,并且我们将向量加入子集时还要考虑此向量是否已经存在。combination 1参考博客
http://blog.csdn.net/sinat_24520925/article/details/47058935
本题为了避免超时,采用了上面博客的第二种算法,代码如下:
class Solution {public:vector<vector<int>> res; vector<int> pre; void cm(vector<int>& p, int tag,int l) { if(l==pre.size()) return; int temp=accumulate(p.begin() , p.end() , 0); if(temp==tag) { sort(p.begin(),p.end());int flag=0;for(int j=0;j<res.size();j++){if(res[j].size()==p.size()){int t;for(t=0;t<p.size();t++)        {if(res[j][t]!=p[t]){break;}}if(t==p.size()){flag=1;//已有相同的并加入到了res}}}if(flag==0)res.push_back(p); return ; } else if(temp>tag) return; else { for(int i=l+1;i!=pre.size();i++) { p.push_back(pre[i]); cm(p,tag,i); p.pop_back(); } } }    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {        if(candidates.size()==0) return res;         if(target<=0) return res;         int len=candidates.size(); sort(candidates.begin(),candidates.end()); pre=candidates; vector<int> tmp; cm(tmp,target,-1); return res;    }};



0 0
原创粉丝点击