具体原理详见Gosper’s Hack
代码实现如下
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1<<25;
int num[N];
int main(){
int n,m, cnt = 0;
cin >> n >> m;
if(n == 0 or m == 0) return 0;
int cur = (1<<m)-1, limit = 1<<n;
//Gosper's Hack
while(cur < limit){
num[cnt++] = cur;
int lb = cur & -cur;
int r = cur + lb;
cur = (((r^cur) >> 2) / lb) | r;
}
for(int i = cnt-1; ~i; i--){
for(int j = n-1; ~j; j--){
if(num[i] >> j & 1)
cout << n-j << ' ';
}
cout << endl;
}
return 0;
}