從 1~n 這 n 個整數中隨機選取任意多個,輸出所有可能的選擇方案。
輸入格式
輸入一個整數n。
輸出格式
每行輸出一種方案。
同一行內的數必須升序排列,相鄰兩個數用恰好1個空格隔開。
對於沒有選任何數的方案,輸出空行。
本題有自定義校驗器(SPJ),各行(不同方案)之間的順序任意。
數據範圍
1≤n≤15
輸入樣例:
3
輸出樣例:
3
2
2 3
1
1 3
1 2
1 2 3
/*
主要思想:任意選擇多個,那麼我們只需要判斷這個數字是否選擇即可
*/
#include <iostream>
using namespace std;
int nums[16];//0-代表這個數字不用,1-代表這個數字用了
int n;
void dfs(int index)//決定index這個數字是否使用
{
//index == n,代表已經判斷到最後一個位置了
if(index == n)
{
for(int i = 0; i < n; i++)
{
if(nums[i] == 1)
cout << i+1 << " ";
}
cout << endl;
return;
}
nums[index] = 1;//這個數字使用
dfs(index+1);//去判斷下一個數字
nums[index] = 0;//這個數字不使用
dfs(index+1);
}
int main()
{
cin >> n;
dfs(0);
return 0;
}
/*
主要思想:用2進制數字代表這個數字是否取用0代表不取用,1代表取用
則是輸出所有2進制數所有可能
*/
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double n;
cin >> n;
int c = pow(2,n);//計算出對應的十進制數字
for(int i = 0; i < c; i++)//遍歷十進制,即遍歷所有二進制
{
//取出第j位置上是1還是0
for(int j = 0; j < n; j++)
{
if((i >> j&1) == 1)//爲1,代表取用
{
cout << j+1 << " ";
}
}
cout << endl;
}
return 0;
}