您的位置:首页 > 其它

Combination Sum

2016-01-19 22:20 295 查看

每日算法——leetcode系列

问题 Combination Sum

Difficulty: Medium

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) {

}
};


翻译

和的组合

难度系数:中等

给定一个一些数组成的候选集合C,和一个目标数T。现从C中选出一些数,求所有不同的取数方案使其累加和恰好等于T。

C中的每个数都可以取若干次。

注意

所有的数(包括目标数)都为正整数

组合中的元素(a1, a2, … , ak) 不能为降序排列。(ie, a1 ≤ a2 >≤ … ≤ ak)

不能有重复的组合方案

例如:候选集合
2,3,6,7
和目标值
7
,

答案为:

[7]

[2, 2, 3]


思路

此题有点像是钱的面值为1、5、10,然后用这些面值的钱组合成一个特定的数。

不考虑加和加起来大于Int_Max的情况。

由于每个数可以重复,可于抽象成树,root结节点有候选集合的总个数个子节点,其中每个子节点的子节点是子节点本身,重复下去。

以候选集合
2,3,6,7
为例

root节点往下,有节点
2,3,6,7
,从左取
2
这个节点push进
vector<int>
,每push一次将目标值减去取的节点值,如果剩余的值大于0,继续取,按深度优先取,
2
的子节点还是
2
,···

还是画图比较清晰,找到好的画圈工具再加上

代码

class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
len = static_cast<int>(candidates.size());
temAndidates = candidates;
vector<int> combination;
dfs(combination, target, 0);
return result;
}

private:
int len;
vector<int> temAndidates;
vector<vector<int> > result;

void dfs(vector<int>& combination, int remainder,  int tempLen){
if (tempLen >= len) {
return;
}
if (remainder == 0){
result.push_back(combination);
return;
} else {
for (int i = tempLen; i < len; ++i) {
if (remainder < temAndidates[i]){
return;
}
combination.push_back(temAndidates[i]);
dfs(combination, remainder - temAndidates[i], i);
combination.pop_back();
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: