Blue Bridge Cup ADV-188 permutation number java

Problem Description

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

Reference Code

package 排列数;

import java.util.ArrayList;

import java.util.Scanner;

public class Main {
	static int n;
	static ArrayList<Integer> list = new ArrayList<Integer>();
	static int[] arr = {0,1,2,3,4,5,6,7,8,9};
	static boolean[] check = new boolean[arr.length];
	static int count = 0;
public static void main(String[] args) {
	Scanner sr = new Scanner(System.in);
	n = sr.nextInt();
	sr.close();
	//进入递归
	f(0);
}
private static void f(int length) {
	if (length == 10) {
		//System.out.println(list);
		count++;//计数器,第count个全排列
		if (count == n) {
			for (Integer item : list) {
				System.out.print(item);
			}
			System.exit(0);//结束程序
		}
	}else {
		for (int i = 0; i < 10; i++) {
			if (!check[i]) {
				check[i] = true;
				list.add(arr[i]);
				f(length+1);
				check[i]= false;
				list.remove(list.size()-1);
			}
		}
	}
}
}

 

Guess you like

Origin blog.csdn.net/qq_40185047/article/details/114883926