您的位置:首页 > 其它

[LeetCode] Combination Sum II

2012-10-29 17:36 393 查看
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的DFS,有一点需要注意,如何避免重复。如果两个数相同,我们先用前一个数,只有当前一个数用了,这个数才能使用。

例如:1 1。

当我们要使用第二个1时,我们要检查他的前面一个1是否使用了,当未被使用时第二个1就不能使用。

class Solution {
private:
vector<vector<int> > ret;
vector<int> a;
public:
void solve(int dep, int maxDep, vector<int> &num, int target)
{
if (target < 0)
return;

if (dep == maxDep)
{
if (target == 0)
{
vector<int> res;
for(int i = 0; i < maxDep; i++)
for(int j = 0; j < a[i]; j++)
res.push_back(num[i]);
ret.push_back(res);
}

return;
}

for(int i = 0; i <= min(target / num[dep], 1); i++)
{
a[dep] = i;

if (i == 1 && dep > 0 && num[dep-1] == num[dep] && a[dep-1] == 0)
continue;

solve(dep + 1, maxDep, num, target - i * num[dep]);
}
}

vector<vector<int> > combinationSum2(vector<int> &num, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(num.begin(), num.end());
a.resize(num.size());
ret.clear();
if (num.size() == 0)
return ret;

solve(0, num.size(), num, target);

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