題目連結:https://zerojudge.tw/ShowProblem?problemid=d471
解法1:遞迴
#include <iostream>
#include <string>
using namespace std;
int n;
string s;
void f(int now){
if(now == n){
cout << s << 'n';
return;
}
s[now] = '0';
f(now+1);
s[now] = '1';
f(now+1);
}
int main(){
while(cin >> n){
s.resize(n);
f(0);
}
}
解法2:二進位
列舉 0 到 2^(n-1),並轉成二進位輸出。
(1 << n 等於 2^n)
#include <iostream>
using namespace std;
int main(){
int n;
while(cin >> n){
int N = (1 << n);
for(int i=0; i<N; i++){
//decimal to binary
for(int j=n-1; j>=0; j--){
if(i & (1 << j)) cout << '1';
else cout << '0';
}
cout << '\n';
}
}
}