有一個集合由A-Z 26個字母俗稱,打印這個集合所有的子集(不能使用遞歸)

假設ABC,三個我們一共有8個子集,分別如上圖所示排列。那麼我們就可以通過這個規律排列出所有的子集。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void Prinf_jihe(int n)
{
    char str[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int maxnum = 1 << n;   //2^n,會有多少個子集

    for(int i = 0; i < maxnum; i++) //子集個數
    {
        for(int j = 0; j < n; j++) //每個子集二進制右數第幾位
        {
            if((i&(1<<j)) != 0)
                {
                    cout << str[j];
                }
        }
        cout << endl;
    }
}

int main()
{
    Prinf_jihe(3);
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章