public String getPermutation1(int n, int k) {
final int[] arr = new int[]{1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
boolean[] visited = new boolean[n + 1];
Arrays.fill(visited, false);
StringBuilder permutation = new StringBuilder();
for (int i = n - 1; i >= 0; i--) {
int cnt = arr[i]; // 是指当前i之下的排列个数
for (int j = 1; j <= n; j++) {
if (visited[j]) {
continue;
} // 控制元素重复性的
// j 是一个待添加的元素,可以跳过的元素个数为 j 所在的这一层cnt个元素
if (k > cnt) {
k -= cnt;
continue;
} // 其作用已不是剪枝了,而是为了跳过元素,跳过前一个元素下的所有节点,再添加后一个节点
visited[j] = true;
permutation.append(j);
break;
}
}
return permutation.toString();
}
【LeetCode 60】排列序列
最新推荐文章于 2024-04-26 16:57:38 发布