全排列
| Time Limit: | 2000MS | Memory Limit: | 65535KB |
|---|---|---|---|
| Total Submissions: | 425 | Accepted: | 150 |
Description:
对1-n的数进行全排列,例如n为2的时候,应该输出1 2,2 1。
Input:
只有一个整数n,其中n<=10.当n=0时答案为0。
Output:
1-n的全排列。
Sample Input:
3
Sample Output:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
Source:
#include<stdio.h>
int n;
bool mark[105];
int stack[105],top;
void dfs()
{
if(top==n)
{
for(int i=0;i<top;i++)
{
if(i==0)
printf("%d",stack[i]);
else
printf(" %d",stack[i]);
}
printf("\n");
return ;
}
for(int i=1;i<=n;i++)
if(mark[i]==0)
{
mark[i]=1;
stack[top++]=i;
dfs();
top--;
mark[i]=0;
}
}
int main()
{
while(scanf("%d",&n)==1)
{
if(n==0)
{
printf("0\n");
return 0;
}
else
dfs();
return 0;
}
}
\
\