【LeetCode】Combination Sum II

来源:互联网 发布:ai软件下载最新版 编辑:程序博客网 时间:2024/06/03 17:22

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] 

思路:见程序,每次将和记下来,知道等于或者大于就return,将这个路径加入到返回的ret的vector中,其中注意每个数字不能重复使用。

class Solution {public:    void comb(vector<int> num,int index,int sum,int target,vector<vector<int> > &ret,vector<int> &path){        if(sum>target)return;        if(sum == target){            ret.push_back(path);            return;        }        for(int i = index;i<num.size();i++){            path.push_back(num[i]);            comb(num,i+1,sum+num[i],target,ret,path);            path.pop_back();            while(i<num.size()-1 && num[i]==num[i+1])i++;        }    }    vector<vector<int> > combinationSum2(vector<int> &num, int target) {        sort(num.begin(),num.end());        vector<vector<int> > ret;        vector<int> path;        comb(num,0,0,target,ret,path);        return ret;    }};



0 0