首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

subsets(C++兑现)

2013-07-16 
subsets(C++实现)Given a set of distinct integers,?S, return all possible subsets.Note:Elements in a

subsets(C++实现)

Given a set of distinct integers,?S, return all possible subsets.

Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

    ?

    For example,
    If?S?=?[1,2,3], a solution is:

    [  [3],  [1],  [2],  [1,2,3],  [1,3],  [2,3],  [1,2],  []]

    ?

    class Solution {public:    vector<vector<int> > subsets(vector<int> &S) {        vector<vector<int> > ret;        if(S.size() == 0) return ret;        sort(S.begin(), S.end());        vector<int> tmp;        dfs(S, 0, tmp, ret);        return ret;    }        void dfs(vector<int> &S, int beg, vector<int> tmp, vector<vector<int> > &ret) {        ret.push_back(tmp);        if(beg >= S.size()) return;        for(int i = beg; i < S.size(); ++i) {            tmp.push_back(S[i]);            dfs(S, i+1, tmp, ret);            tmp.pop_back();        }    }};

    ?

热点排行