提供三种解法
第一种为非递归型代码
第二种为递归代码
第三种同为非递归型代码,但相对暴力,不过也能AC
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
inline ll read() {
ll f=1,x=0;
char ch;
do {
ch=getchar();
if(ch=='-')f=-1;
} while(ch>'9'||ch<'0');
do {
x=x*10+ch-'0';
ch=getchar();
} while(ch>='0'&&ch<='9');
return f*x;
}
ll n;
struct sth{
ll pos,k,state;
};
int main() {
n=read();
stack<sth>S;
sth a;a.pos=0,a.k=0,a.state=0;
S.push(a);
while(!S.empty())
{
sth e=S.top();
S.pop();
if(e.pos==0)
{
if(e.k==n){
for(int i=0;i<n;i++)
if(e.state>>i&1)
printf("%d ",i+1);
puts("");
continue;
}
e.pos=1;
S.push(e);
S.push({0,e.k+1,e.state});
}
else if(e.pos==1){
e.pos=2;
S.push(e);
S.push({0,e.k+1,e.state|(1<<e.k)});
}
else continue;
}
return 0;
}
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
inline ll read() {
ll f=1,x=0;
char ch;
do {
ch=getchar();
if(ch=='-')f=-1;
} while(ch>'9'||ch<'0');
do {
x=x*10+ch-'0';
ch=getchar();
} while(ch>='0'&&ch<='9');
return f*x;
}
ll n;
void dfs(int k,int S){
if(k==n){
for(int i=0;i<n;i++)
if(S>>i&1)
printf("%d ",i+1);
puts("");
return ;
}
dfs(k+1,S);
dfs(k+1,S|(1<<k));
}
int main() {
n=read();
// puts("");
dfs(0,0);
return 0;
}
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
inline ll read() {
ll f=1,x=0;
char ch;
do {
ch=getchar();
if(ch=='-')f=-1;
} while(ch>'9'||ch<'0');
do {
x=x*10+ch-'0';
ch=getchar();
} while(ch>='0'&&ch<='9');
return f*x;
}
ll n,vis[20],AC[200];
inline void dfs(ll k,ll m)
{
if(k==m+1){
for(int i=1;i<=m;i++){
printf("%lld ",AC[i]);
}
puts("");
}
for(int i=1;i<=n;i++){
if(!vis[i]&&i>AC[k-1]){
vis[i]=1;
AC[k]=i;
dfs(k+1,m);
vis[i]=0;
}
}
}
int main() {
n=read();
puts("");
for(int i=1;i<=n;i++){
memset(vis,0,sizeof(vis));
dfs(1,i);
}
return 0;
}