专题:Permutation
原题:
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.
» Solve this problem
方法:
1. 建一个数组存阶乘,另一个数组存访问过的节点
2. 从n-1到0简历for-loop,其中建一个while-loop, 如果k大于对应正在遍历的i的阶乘,把k减小i的阶乘
3. 减小k的同时,增加tmp的值,这个while-loop结束条件是k小于i的对应阶乘
4. 接下来,简历一个for-loop,从0到n-1, 如果当前值小于对应的tmp,并且已被访问过,那么tmp继续加一
5. 把tmp的值加到stringbuilder后面,标记tmp对应的位数为已访问,进入下一轮大循环
代码:
public class Solution {
public String getPermutation(int n, int k) {
// Start typing your Java solution below
// DO NOT write main() function
boolean[] visited = new boolean[n];
int[] factor = new int[n];
factor[0] = 1;
for(int i=1; i<n; i++)
factor[i] = factor[i-1]*i;
StringBuilder sb = new StringBuilder();
for(int i=n-1; i>=0; i--){
int tmp = 1;
while(k > factor[i]){
tmp++;
k -= factor[i];
}
for(int j=0; j<n; j++)
if(j+1<=tmp && visited[j])
tmp++;
sb.append(tmp);
visited[tmp-1] = true;
}
return sb.toString();
}
}
小结:
这题运用了Permutation的标志性结构:boolean[] visited,当全局考虑时,布尔数组对于已访问的记录是必须的。和Next Permutation一样,结构不复杂,方法有点绕,不易理解。