leetcode: Combination Sum II

来源:互联网 发布:软件项目经理工资待遇 编辑:程序博客网 时间:2024/04/28 14:45

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] 

这题和Combination Sum I一样的,只是增加点限制条件而已,传下标的时候传当前下标的下一个,循环里标记下当前数是不是和之前的一样

class Solution {public:    vector<vector<int> > combinationSum2(vector<int> &num, int target) {        vector< int> cur;        sort( num.begin(), num.end());        _combinationSum( num, cur, 0, target, 0);        return res;    }    vector< vector< int> > res;    void _combinationSum( vector< int> &num, vector< int> & cur, int pos, int target, int cur_sum){        if( cur_sum == target){            res.push_back(cur);            return;        }        int flag = 0;        for( int i = pos; i < num.size(); ++i){            if( flag == num[i])//这里标记如果当前数字和之前的数字是一样的就跳过,也是保证结果唯一                continue;            if( num[i] + cur_sum > target)                break;//因为前面对数组排序了这里就可以改成break,不然是continue            flag = num[i];            vector< int> tmp = cur;            tmp.push_back( flag);            _combinationSum( num, tmp, i+1, target, cur_sum+flag);//这里下标传i+1因为每个只能用一次        }    }};


0 0
原创粉丝点击