leetcode No40. Combination Sum II

来源:互联网 发布:asp微商城源码 编辑:程序博客网 时间:2024/06/17 19:35

Question:

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums toT.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • 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]]

找出数组中元素之和等于target,且不重复

Algorithm:

BFS然后去除重复的

Aceepted Code:

class Solution {public:    vector<vector<int>> res;    void BFS(vector<int> s,int index,vector<int> pre,int tar)    {    int N = s.size();    if (index>N)return;    for (int i=index;i<N;i++)    {        vector<int> tmp(pre);        tmp.push_back(s[i]);    if(s[i]<tar)    {    BFS(s,i+1,tmp,tar-s[i]);    }    else if(s[i]==tar){    res.push_back(tmp);    }    else        return;    }    }    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {        sort(candidates.begin(),candidates.end());        vector<int> pre;        BFS(candidates,0,pre,target);        sort(res.begin(),res.end());  //unique()函数只能返回相邻重复元素        //unique(begin(),end())把重复元素移到容器底部,返回第一个重复元素的指针,指针后面的元素都是需要去除的        vector<vector<int>>::iterator unique_end=unique(res.begin(),res.end());            res.erase(unique_end,res.end());   //删除unique_end到res.end()的所有元素                return res;    }};




0 0
原创粉丝点击