把 1∼n 这 n 个整数排成一行后随机打乱顺序,输出所有可能的次序。
输入格式: 输入一个整数 n,1≤n≤9。
输出格式: 按照从小到大的顺序输出所有方案,每行 1 个。
首先,同一行相邻两个数用一个空格隔开。
其次,对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面。
输入样例:
3
输出样例:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
代码详解:
import java.util.Scanner;
import java.io.PrintWriter;
public class Main {
static int[] stu=new int[10];
static int[] vis=new int[10];
static int n;
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
dfs(1,0);
out.flush();
}
public static void dfs(int u,int ans) {
if(ans==n)
{
for(int i=0;i<n;i++)
out.print(stu[i]+" ");
out.print("\n");
}
for(int i=1;i<=n;i++)
{
if(vis[i]==0)
{
vis[i]=1;
stu[ans]=i;
dfs(i,ans+1);
vis[i]=0;
}
}
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有