您的位置:首页 > 其它

Combination Sum II

2015-07-25 19:06 337 查看
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]
 

解题思路:

和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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: