leetcode--Combination Sum II

来源:互联网 发布:冒险岛322数据库 编辑:程序博客网 时间:2024/06/10 07:27

1.问题

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] 

2.分析

如果像上一道题那样,决定每个元素时,都从0开始遍历candidates[ ]所有元素的话,很难保证candidates[ ]的元素只被使用一次,所以决定子数组的第k个元素的值时,要从第k-1位的值在candidates[ ]对应的位置的下一位开始遍历。那么又要保证子数组有序,可以先对candidates[ ]排序。排序后有可能有连续的相同的元素,比如例子中,1,1,2,5,6,7,10.这样会出现两个1,2,5和两个1,7.这时就要跳过第2个1.


3.实现

class Solution {public:    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {        sort(candidates.begin(),candidates.end());        combination(candidates,target,0,0,0);        return all;    }private:    vector<vector<int>> all;    vector<int> one;    void combination(vector<int>& candidates,int target,int k,int s,int sum) {        int pre = -1;        for(int i=s;i<candidates.size();++i) {            if(candidates[i] == pre) continue;            sum += candidates[i];            one.push_back(candidates[i]);            if(sum == target) {                all.push_back(one);            }            else if(sum < target) {                combination(candidates,target,k+1,i+1,sum);            }            pre = one.back();            one.pop_back();            sum -= candidates[i];        }    }};


0 0