给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。
按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:
"123"
"132"
"213"
"231"
"312"
"321"
给定 n 和 k,返回第 k 个排列。
说明:
给定 n 的范围是 [1, 9]。
给定 k 的范围是[1, n!]。
示例 1:
输入: n = 3, k = 3
输出: "213"
示例 2:
输入: n = 4, k = 9
输出: "2314"
深度遍历,回溯算法,先构造一个包含从1到n的集合,只需要遍历到第k个字符串即可,用一个数组保存上k值
public static String getPermutation(int n, int k) {
List<Integer> nums = new ArrayList<>();
int temp = 1;
while (temp <= n) {
nums.add(temp);
temp++;
}
int[] index = new int[1];
index[0] = k;
return getPermutation(0, nums, index);
}
当遍历的开始指标超过集合大小时说明一个需要的字符串已经可以生成了,判断是否是第k个字符串,是的话就构造字符串返回,否则的话返回空,第一次遍历集合时,start是0,也就是对应i的数字需要放到0号位置,i上的数字移除,也就是前移,这样的话每个数字都有机会成为字符串的第一个字符,递归里面start+1,也就类似,每个数字都会处于字符串任何一个位置
public static String getPermutation(int start, List<Integer> nums, int[] index) {
if (start >= nums.size()) {
index[0]--;
if (index[0] == 0) {
StringBuilder sb = new StringBuilder();
for (Integer i : nums) {
sb.append(i);
}
return sb.toString();
}
}
for (int i = start; i < nums.size(); i++) {
shift(nums, start, i);
String s = getPermutation(start + 1, nums, index);
if (s != null) {
return s;
}
shift(nums, i, start);
}
return null;
}
对应数字前移
public static void shift(List<Integer> nums, int a, int b) {
int temp = nums.get(b);
nums.remove(b);
nums.add(a, temp);
}
还有一种方式是先求出第一个数字,然后剩下的再回溯求出,开始递归之前会把结果的第一个数字放到第一位,factorial代表每个n对应的字符串的总和,先获取n - 1总共有多少个组合,再根据k判断出开头是那个,最后再减去忽略的字符串,最后求出以集合中c下标的数字为开头的第k - b * c的字符串。
public static String getPermutation(int n, int k) {
int[] factorial = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
int b = factorial[n - 1]
int c = (k - 1) / b;
int[] index = new int[1];
index[0] = k - b * c;
List<Integer> nums = new ArrayList<>();
int temp = 1;
while (temp <= n) {
nums.add(temp);
temp++;
}
shift(nums, 0, c);
return getPermutation(0, nums, index, factorial);
}
public static String getPermutation(int start, List<Integer> nums, int[] index, int[] factorial) {
if (start >= nums.size()) {
index[0]--;
if (index[0] == 0) {
StringBuilder sb = new StringBuilder();
for (Integer i : nums) {
sb.append(i);
}
return sb.toString();
}
}
for (int i = start; i < nums.size(); i++) {
shift(nums, start, i);
String s = getPermutation(start + 1, nums, index, factorial);
if (s != null) {
return s;
}
shift(nums, i, start);
}
return null;
}