您的位置:首页 > 职场人生

leetcode之Combination Sum II

2016-03-10 11:17 525 查看
题目:

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


解答:

class Solution {
private:
void backtracking(vector<int>& candidates, int target, int pos, vector<int>& temp, vector<vector<int>>& result)
{
int n = candidates.size();
if(target==0)
result.push_back(temp);
if(pos>=n || target<=0)
return;

int nextPos = pos+1;
while(nextPos<n && candidates[nextPos]==candidates[pos])
{
nextPos++;
}

int i, j;
for(i=0; i<=nextPos-pos; i++)
{
if(target-i*candidates[pos]<0)
break;
for(j=0; j<i; j++)
temp.push_back(candidates[pos]);
backtracking(candidates, target-i*candidates[pos], nextPos, temp, result);
for(j=0; j<i; j++)
temp.pop_back();
}
}

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

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