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.
public class Solution {
public String getPermutation(int n, int k) {
int t = 1;;
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= n; i++) {
t *= i;
list.add(i);
}
k--;
StringBuilder sb = new StringBuilder();
for (int i = n; i >= 1; i--) {
t = t/i;
int index = k/t;
sb.append(list.get(index));
list.remove(index);
k = k % t;
}
return sb.toString();
}
}
本文介绍了一种算法,用于找出数字集合 [1,2,3,...,n] 中第 k 个字典序排列。通过递减计数和列表移除的方法,实现了对 n 和 k 的输入返回对应的排列字符串。
371

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



