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 for n = 3:
"123""132""213""231""312""321"
Given n and k, return the kth permutation sequence.
Note:
- Given n will be between 1 and 9 inclusive.
- Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3 Output: "213"
Example 2:
Input: n = 4, k = 9 Output: "2314"
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 for n = 3:
"123""132""213""231""312""321"
Given n and k, return the kth permutation sequence.
Note:
- Given n will be between 1 and 9 inclusive.
- Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3 Output: "213"
Example 2:
Input: n = 4, k = 9 Output: "2314"
把1~n个的数字按字典序排列,然后返回第k个排列。
不需要把所有排序都列出来,首先,筛选第一位,则后面的n-1位有(n-1)!的排列,则用看k是n-1的多少倍,则可以选出第一个数字。下一个数字则k - 【k / (n - 1)! 】* (n-1)! 以此列推。
class Solution {
public int jiecheng (int k) {
int rt = 1;
for (int i = 1; i <= k; i++)
rt *= i;
return rt;
}
public String getPermutation(int n, int k) {
String ans = "";
//用一个数组储存已经选过的数字
boolean []visited = new boolean[n];
int count = 0;
int num = n;
n--;
while (count < num) {
int jk = jiecheng(n);
//计算出,应该选择剩余数字的第几个。
int select = ( k - 1) / jk;
int index = 0;
int i = 0;
//选出未未选出的第select个
while (true) {
if (!visited[i]) {
if (index == select) {
ans += (i + 1);
visited[i] = true;
break;
}
index++;
}
i++;
}
//减去当前排序数量,进入下一位
k = k - select * jk;
count++;
n--;
}
return ans;
}
}
本文介绍了一种高效算法,用于求解1到n数字的字典序排列中第k个排列的问题。通过数学方法筛选每一位上的数字,避免了全排列的生成,显著提高了计算效率。
225

被折叠的 条评论
为什么被折叠?



