problem:
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]
是上一题的变形,这里每个数字只允许使用一次
thinking :
(1)DFS算法,路径深度每次+1,但是否采用该层数字则不一定!!!
code:
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;
}
};