给出集合 [1,2,3,...,n],其所有元素共有 n! 种排列。
按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:
"123"
"132"
"213"
"231"
"312"
"321"
给定 n 和 k,返回第 k 个排列。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutation-sequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.Arrays;
import java.util.Scanner;
class Solution {
public String getPermutation(int n, int k) {
int s = 1;
for (int i = 2; i <= n; ++i) {
s *= i;
}
StringBuilder sb = new StringBuilder();
int[] valid = new int[n + 1];
Arrays.fill(valid, 1);
while (n > 0) {
s /= n;
int i = 1;
int cnt = 0;
int r = k % s == 0 ? (k / s) : (k / s + 1);
for (; i <= valid.length; ++i) {
cnt += valid[i];
if (cnt == r) {
valid[i] = 0;
break;
}
}
sb.append(i);
k -= (r - 1) * s;
n--;
}
return sb.toString();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
System.out.println(new Solution().getPermutation(in.nextInt(), in.nextInt()));
}
}
}