蓝桥杯 排列数(java题解)

这道蓝桥杯题目要求根据输入的整数n,输出0到9十个数字全排列中的第n个。题解采用递归遍历的方法,解决这个问题。样例输入1时,输出的全排列为0123456789,且保证0 < n <= 10!。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:排列数
0、1、2三个数字的全排列有六种,按照字母序排列如下:
  012、021、102、120、201、210
输入一个数n,求0~9十个数的全排列中的第n个(第1个为0123456789)。
输入格式  
一行,包含一个整数n
输出格式  
一行,包含一组10个数字的全排列样例输入1样例输出0123456789数据规模和约定  
0 < n <= 10!

题解:递归遍历

//for循环里若不在新的ArrayList()中操作, 进入下一个循环时两个数组都是改变了的
import java.util.*;


public class Main{

    public static int count = 0;
    public static int n = 0;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        n = in.nextInt();

        ArrayList<Integer> list = new ArrayList<Integer>();
        for(int i=0;i<10;i++) {
            list.add(i);
        }
        f(list, new ArrayList<Integer>());

    }

    public static void f(ArrayList<Integer> a, ArrayList<Integer> b) {
        if(b.size() == 10) {
            count ++;
            if(count == n) {
                for(Integer i : b) {
                    System.out.print(i.toString());
                }
                System.exit(0);
            }
            return;
        }

        for(int i=0;i<a.size();i++) {
            ArrayList<Integer> c = new ArrayList<Integer>(a);
            ArrayList<Integer> d = new ArrayList<Integer>(b);
            d.add(a.get(i));
            c.remove(i);
            f(c, d);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值