combination sumII

题目描述

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 (a 1, a 2, … , a k) must be in non-descending order. (ie, a 1a 2 ≤ … ≤ a k).
  • The solution set must not contain duplicate combinations.

For example, given candidate set10,1,2,7,6,1,5and target8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]

注:给定集合里面的数每次只能使用一次!!!访问完就不能再访问此位置!!

实现代码:

                class Solution {
public:
    vector<vector<int>> res;
    vector<vector<int> > combinationSum2(vector<int> &num, int target) {
        vector<int> tmp;
        sort(num.begin(),num.end());
        combinationDFS(num,tmp,0,target);
        sort(res.begin(),res.end());    //对结果排序;
        res.erase(unique(res.begin(),res.end()),res.end());  //删除掉重复结果;
        return res;
    }
    void combinationDFS(vector<int> &num,vector<int> &tmp,int index,int target)
    {
        if(target==0)
        {
            res.push_back(tmp);
            return;
        }
        else
        {
            for(int i=index;i<num.size();i++)
            {
                if(num[i]>target) return;
                tmp.push_back(num[i]);
                combinationDFS(num,tmp,i+1,target-num[i]); //深度搜索下一个,不允许重复选取当前元素;
                tmp.pop_back();
            }
        }
    }
};

C++容器类函数操作

Unique去重函数

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页