求集合{1,2,...,n}的长度小于M(M<=n)的所有子集

来源:互联网 发布:linux常用查看命令 编辑:程序博客网 时间:2024/04/29 13:46

求集合{1,2,…,n}的长度小于M(M<=n)的所有子集

说明

参考http://blog.csdn.net/unclerunning/article/details/51112124 中提到的按字典顺序排序集合{1,2,…,n}的所有子集。
以求集合{1,2,3,4}所有长度小于2的子集为例:


这里写图片描述

/*这个函数用来获取所有长度小于M的子集*/void subset_lengthM(int const &n,vector<vector<int>> &result){    int  M;    cout << "这个函数用来获取所有长度小于M的子集,并按字典顺序排序" << endl;    cout << "请输入M" << endl;    cin >> M;    int pos(0);    vector<int> *temp;    result.push_back(*new vector<int>());//初始添加一个没有大小的集合,也就是空集    if (M == 0) return;    temp = new vector<int>();    temp->push_back(1); pos++;    while (true)    {        result.push_back(*temp);//将上一轮循环得到的结果保存        if ((*temp)[pos - 1] < n&&pos<M){//最右边的元素不是最大值n时,继续往右走            temp = new vector<int>(*temp);            temp->push_back((*temp)[pos - 1] + 1); pos++;        }        else if ((*temp)[pos - 1]==n&&pos == 1){//{n}的情况,退出循环            break;        }        else if ((*temp)[pos - 1] < n){//向右shift            //新开辟大小为pos(M)的vector            vector<int> *temp1 = new vector<int>(pos);            copy(temp->begin(), temp->begin() + pos, temp1->begin());            temp = temp1;            (*temp)[pos - 1]++;//将第pos个元素加1。        }        else{//{...i,n}的情况,这个集合的下一个集合因该是{...i+1}            pos--;            //新开辟大小为pos的vector            vector<int> *temp1 = new vector<int>(pos);            copy(temp->begin(), temp->begin() + pos, temp1->begin());            temp = temp1;            (*temp)[pos - 1]++;//将第pos个元素加1。        }    }}int main(){    vector<vector<int>> result;    int n;    cout << "输入集合上限n:" << endl;    cin >> n;    cout << "subset_lengthM:------------------------" << endl;    subset_lengthM(n,result);       for (int i(0); i < result.size(); i++){        cout << "{";        copy(result[i].begin(), result[i].end(), ostream_iterator<int>(cout));        cout << "}";        cout << endl;    }    system("pause");    return 0;}
0 0
原创粉丝点击