题目
/**
* LeetCode60 n个数的排列组合找出第k个排列
* The set [1 ,2 ,3 ,…,n]contains a total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3 ):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the k th permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
时间限制:1 秒
*/
分析
乍看是1~N这N个数字的全排列
变化是,每排好一个就计数,计数到k就输出当前排好的这个数
注意,如何控制数字按从小到大出现?在算法思维(递归)训练:输出字符串字符的全排列 中无需考虑顺序,而且经过实验输出的数字并非完全按从小到大排列。所以需要微调swap函数
代码
public class PermutationSequence {
int count ;
String result;
public String getPermutation(int n, int k) {
char [] arr = new char [n];
for (int i = 0 ; i < n; i++)
arr[i] = (char ) ('1' + i);
permutation(arr, 0 , k);
return result;
}
private void permutation(char [] arr, int index , int cc) {
if (index == arr.length) {
count ++;
if (count == cc)
result = String.valueOf(arr);
}
for (int k = index ; k < arr.length; k++) {
swap1(arr, index , k);
permutation(arr, index + 1 , cc);
swap2(arr, index , k);
}
}
private void swap1(char [] arr, int index , int k) {
char tmp = arr[k];
for (int i = k; i > index ; i--) {
arr[i] = arr[i - 1 ];
}
arr[index ] = tmp;
}
private void swap2(char [] arr, int index , int k) {
char tmp = arr[index ];
for (int i = index ; i < k; i++) {
arr[i] = arr[i + 1 ];
}
arr[k] = tmp;
}
public static void main(String[] args) {
Instant now = Instant.now();
System.out.println(new PermutationSequence().getPermutation(9 ,362880 ));
System.out.println("毫秒:" +(Instant.now().toEpochMilli()-now.toEpochMilli()));
}
}