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里总会超时。这样的时间复杂度确实有点太高了。