您的位置:首页 > 其它

Leetcode-39.Combination Sum

2015-12-27 04:35 274 查看
Problem description :

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]

Analysis :

1. What is a partial solution and when is it finished?

Partial Solution is the combination, finished when sum of the set is equal to target.

2. How to find all the partial solutions?

Using a for-loop to traverse all the possible elements in candidates.

3. When to make recursive calls?

when add a new element to the partial solution, we use recursive call to generate all the results.

Remember to recover to the previous status once a partial solution is done,

Code:

class Solution {
public:
vector<vector<int> > combinationSum(vector<int>& candidates, int target) {
int n = candidates.size();
vector<int> v;
vector<vector<int> > res;
if (n == 0) return  res;
sort(candidates.begin(), candidates.end());
combine(res, v, candidates, target, 0);
return res;
}

void combine(vector<vector<int> >& res, vector<int>& v, vector<int>& candidates, int target, int start)
{
if (target == 0)
{
res.push_back(v);
return ;
}

for (int i = start; i < candidates.size() && candidates[i] <= target; ++i)//   <=
{
v.push_back(candidates[i]);
combine(res, v, candidates, target - candidates[i], i);
v.pop_back();
}
}
};


We also have dynamic programming solution:

This is just like a coin change/knapsack problem,.We need to create a vector of the size of target. And for each o(1)…o(target) we get the values. And if in between we find any sum == target, add that into the result

class Solution {
public:
vector<vector<int> > combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<vector<int> > res;
vector<vector<vector<int> > > dp(target + 1, vector<vector<int>>());
dp[0].push_back(vector<int>());
for (auto& num : candidates)
{
for (int j = 0; j <= target - num; ++j)
{
auto s = dp[j];
if (s.size() > 0)
{
for (auto& t : s)
t.push_back(num);
dp[j + num].insert(dp[j + num].end(), s.begin(), s.end());

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