60. Permutation Sequence
- Total Accepted: 65886
- Total Submissions: 249649
- Difficulty: Medium
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.
刚开始用全排列的常规方法,DFS进行顺序查找,超时
public class Solution {
static int index = 0;
public String getPermutation(int n, int k) {
int[] visited = new int[n];
index = 0;
return permutate(visited, n, k, "");
}
String permutate(int[] visited, int n, int k, String nowStr){
String result = "";
if(nowStr.length() == n){
index++;
return nowStr;
}else{
for(int i = 1; i <= n; i++){
if(visited[i-1] == 0){
visited[i-1] = 1;
nowStr += i;
result = permutate(visited, n, k, nowStr);
//System.out.println(index);
if(index == k){
return result;
}
nowStr = nowStr.substring(0, nowStr.length()-1);
visited[i-1] = 0;
}
}
}
return result;
}
}
转换思路,An, An-1, ..... , A2, A1 An能表示的数字有n!,利用此规律,第一次确定最高位,第二次确定次高位。。。。。。。循环即可得到结果public class Solution {
static int num = 0;
public String getPermutation(int n, int k) {
String result = "";
int[] nums = new int[n+1];
int[] visited = new int[n+1];
nums[1] = 1;
for(int i = 2; i <= n; i ++){
nums[i] = i * nums[i-1];
}
for(int i = n; i >= 2; i --){
int times = k / nums[i-1];
if( k % nums[i-1] != 0){
times++;
k = k % nums[i-1];
}else{
k = nums[i-1];
}
int item = 1;
for(int j = 1; j <= n; j++){
if(visited[j] == 0){
if(times >= 0){
times--;
}
if(times == 0){
result += j;
visited[j] = 1;
break;
}
}
}
}
for(int j = 1; j <= n; j++){
if(visited[j] == 0){
result += j;
visited[j] = 1;
}
}
return result;
}
}