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 kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
开始的想法是DFS,按顺序得到所有的permutation,直到得到第K个为止。
public class Solution {
public String getPermutation(int n, int k) {
boolean[] used = new boolean[n];
List<String> res = new ArrayList<String>();
helper(0, new int[] { 1 }, k, n, used, new StringBuffer(), res);
return res.get(0);
}
public void helper(int level, int[] count, int k, int n, boolean[] used,
StringBuffer str, List<String> res) {
if (level == n) {
if (count[0] < k) {
count[0]++;
return;
} else {
res.add(str.toString());
return;
}
}
if (count[0] <= k) {
for (int i = 1; i <= n; i++) {
if (used[i - 1] == true)
continue;
used[i - 1] = true;
str.append(i);
helper(level + 1, count, k, n, used, str, res);
used[i - 1] = false;
str.deleteCharAt(str.length() - 1);
}
}
}
}在自己机器上没什么问题,不过在LeetCode的OJ里总会超时。这样的时间复杂度确实有点太高了。

本文介绍了一种使用深度优先搜索(DFS)算法来生成包含n!个唯一排列的序列中第k个排列的方法。通过递归地构建排列并检查其是否为所需序号,该算法有效解决了在特定范围内查找特定排列的问题。适用于n介于1到9的场景,特别适合在编程和算法研究中应用。
919

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



