subset 集合子集问题

关于有无重复的集合子集问题 这个帖子讲的很好很详细

下面是我的解法,使用的是第二种思路,排列组合的思想。

/**
 集合中有多少个数,就用多少个位置表示,例如{2,5,8},则给出三位,这三位对应的1,表示取这个元素。相当于排列组合的思想
 所以用0~2^n 来枚举所有可能情况
*/
class Solution {
public:
    vector<vector<int> > subsets(vector<int> &S) {
       vector<vector<int> > ret;
       int len = S.size();
       int n = pow(2,len);
       sort(S.begin(),S.end());
       int idx;
       vector<int> tmp;
       for(int i = 0;i < n;i++){
        idx = 0;
        tmp.clear();
        int p = i;
        while(p){
            if(p % 2)
                tmp.push_back(S[idx]); //把S[]的第idx元素push进来
            idx++;
            p = p/2;
        }
       /* for(int j = 0;j<tmp.size();j++)
            cout << tmp[j] << " ";
        cout<<endl;
       */
        ret.push_back(tmp);
       }
       //cout << ret.size() << endl;
       return ret;
    }
};


有重复的情况:subsets II

#include <set>
class Solution {
public:
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
       set<vector<int> > ret;
       int len = S.size();
       sort(S.begin(),S.end());
       int n = pow(2,len);
       int idx;
       vector<int> tmp;
       for(int i = 0;i < n;i++){
        idx = 0;
        tmp.clear();
        int p = i;
        while(p){
            if(p % 2)
                tmp.push_back(S[idx]); //把S[]的第idx元素push进来
            idx++;
            p = p/2;
        }
        ret.insert(tmp);
       }

       vector<vector <int> > real;
       copy(ret.begin(), ret.end(), back_inserter(real));//这里需要注意,容器的copy函数
       return real;
    }
};

容器的copy函数

[cpp]  view plain copy
  1. template<class InputIterator, class OutputIterator>  
  2.     OutputIterator copy(  
  3.     InputIterator _First, //源容器起始位置  
  4.     InputIterator _Last, //源容器终止位置  
  5.     OutputIterator _DestBeg //目标容器的起始位置  
  6.     );  

back_inserter 是iterator适配器,它使得元素被插入到作为实参的某种容器的尾部,如vector等
http://www.cplusplus.com/reference/iterator/back_inserter/

上面是reference的介绍:

template <class Container>
  back_insert_iterator<Container> back_inserter (Container& x);
Construct back insert iterator
Constructs a  back-insert iterator that inserts new elements at the end of  x. back-insert iterator  is a special type of  output iterator  designed to allow  algorithms  that usually overwrite elements (such as  copy ) to instead insert new elements automatically at the end of the container.

The type of  x  needs to have a  push_back  member function (such as the standard containers  vector deque  and  list ).

用法
std::copy (bar.begin(),bar.end(),back_inserter(foo));


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值