您的位置:首页 > 其它

leetcode题目 寻找和为SUM的集合系列问题

2015-10-06 16:35 429 查看
题目一: Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

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 2,3,6,7 and target 7,

A solution set is:

[7]

[2, 2, 3]

思路: 递归解决,但是从最后提交的结果来看效率并不高,或许还有更好的算法?

代码:

class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<vector<int>> result;
vector<int> temp;

for(auto i=candidates.begin();i!=candidates.end();++i)
{
temp.push_back(*i);
FindSumSet(i,candidates.end(),result,temp,target-*i);
temp.clear();
}
return result;
}

void FindSumSet(vector<int>::iterator begin,vector<int>::iterator end,vector<vector<int>>& result,vector<int> temp ,int target)
{
if(target==0)
{
result.push_back(temp);
return;
}
else if(target<0)
return;
else
{
auto copy_temp=temp;
for(auto i=begin;i!=end;++i)
{
copy_temp=temp;
copy_temp.push_back(*i);
FindSumSet(i,end,result,copy_temp,target-*i);
}
}
return;
}
};


测试结果: 虽然通过了,但是时间效率很差,只击败了6.17%的代码



题目二: 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]

思路: 只是比第一题复杂一点点,把第一题的代码改改就可以,但是也继承了第一题时间效率差的问题。

class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<vector<int>> result;
vector<int> temp;

for(auto i=candidates.begin(),j=i;i!=candidates.end();i=j)
{
temp.push_back(*i);
FindSumSet(i,candidates.end(),result,temp,target-*i);
temp.clear();
while(++j!=candidates.end()&&*j==*i);
}
return result;
}
void FindSumSet(vector<int>::iterator begin,vector<int>::iterator end,vector<vector<int>>& result,vector<int> temp ,int target)
{
if(target==0)
{
result.push_back(temp);
return;
}
else if(target<0)
return;
else
{
auto copy_temp=temp;
for(auto i=begin+1,j=i;i!=end;i=j)
{
copy_temp=temp;
copy_temp.push_back(*i);
FindSumSet(i,end,result,copy_temp,target-*i);
while(++j!=end&*j==*i);
}
}
return;
}
};


测试结果: 虽然通过了,但是时间效率很差,只击败了10.71%的代码

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