Combination Sum II

来源:互联网 发布:画几何图形软件 编辑:程序博客网 时间:2024/05/21 17:44

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 (a1a2, … , 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] 

和第一题不一样的是不能有重复,所以需要利用int prev来判断num[i]是否重复利用。


void dfs(vector<int>& nums, int rest, int level, vector<int>& temp, vector<vector<int> > &result){    if (rest == 0)    {        result.push_back(temp);        return;    }    int prev=-1;    for (int i = level; i < nums.size(); i++)    {        if (prev == nums[i])            continue;        if (rest < nums[i])            return;        prev=nums[i];        temp.push_back(nums[i]);        dfs(nums, rest - nums[i], i+1, temp, result);        temp.pop_back();    }}vector<vector<int> > combinationSum2(vector<int> &nums, int target){    sort(nums.begin(), nums.end());    vector<vector<int> > result;    vector<int> temp;    dfs(nums, target, 0, temp, result);    return result;}



0 0
原创粉丝点击