问题:
给出集合 [1,2,3,...,n],其所有元素共有 n! 种排列。按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:
"123"
"132"
"213"
"231"
"312"
"321"
给定 n 和 k,返回第 k 个排列。
示例 1:
输入:n = 3, k = 3
输出:"213"
示例 2:
输入:n = 4, k = 9
输出:"2314"
示例 3:
输入:n = 3, k = 1
输出:"123"
提示:
1 <= n <= 9
1 <= k <= n!
以下程序实现了这一功能,请你填补空白处内容:
class Solution {
public String getPermutation(int n, int k) {
StringBuilder sb = new StringBuilder();
List<Integer> candidates = new ArrayList<>();
int[] factorials = new int[n + 1];
factorials[0] = 1;
int fact = 1;
for (int i = 1; i <= n; ++i) {
candidates.add(i);
fact *= i;
factorials[i] = fact;
}
k -= 1;
____________________;
return sb.toString();
}
}
解答思路:
以下是填补空白处的代码:
for (int i = n - 1; i >= 0; i--) {int index = k / factorials[i];k %= factorials[i];sb.append(candidates.get(index));candidates.remove(index);
}
完整的代码如下:
class Solution {public String getPermutation(int n, int k) {StringBuilder sb = new StringBuilder();List<Integer> candidates = new ArrayList<>();int[] factorials = new int[n + 1];factorials[0] = 1;int fact = 1;for (int i = 1; i <= n; ++i) {candidates.add(i);fact *= i;factorials[i] = fact;}k -= 1;for (int i = n - 1; i >= 0; i--) {int index = k / factorials[i];k %= factorials[i];sb.append(candidates.get(index));candidates.remove(index);}return sb.toString();}
}
这段代码的思路是:通过计算阶乘数组'factorials',将'k'的值转换为在当前剩余数字中的索引'index'。然后将对应索引的数字添加到结果字符串'sb'中,并从候选数字列表'candidates'中移除该数字。通过从高位到低位依次确定数字,最终得到第'k'个排列的字符串表示。
(文章为作者在学习java过程中的一些个人体会总结和借鉴,如有不当、错误的地方,请各位大佬批评指正,定当努力改正,如有侵权请联系作者删帖。)