一、题目叙述:
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.
Subscribe to see which companies asked this question.
二、解题思路:
Medium题。进步了,好像50%多了
思路:
例如 n=3, k=4,首先计算第一个字符应该是几,因为每个字符在第一位的排列数为sum=!(n - 1)个,排列序x = k -1;所以用sum/x=(k-1)/!(n-1)计算出是,第几个数字,如此时(4-1)/!(3-1)= 1 ,所以第一位应该是第一大的数(还有第0大的数)即2;接下来计算第二位上的数,同理,通过取余得到此时的排列序x值 :x=(k-1)%!(n-1),除以此时的排列数sum=!(n-1-1),得到第二位上数应为剩下数中第1大的数即3,以此类推,直到n个字符都加进字符串为止。
(1)创建一个list,把‘1’到‘n’的字符放进去。
(2)计算排列次序x,计算排列数sum,相除得到此时应将剩下数字中的第几大数字加入字符串(加入后将list中的该字符删除),更新相关参数;直到将全部n个字符加入字符串。
三、源码:
import java.util.ArrayList;
import java.util.Arrays;
public class Solution
{
public String getPermutation(int n, int k)
{
ArrayList<Character> temp = new ArrayList<Character>();
String a = "";
for (int i = 0; i < n; i++)
temp.add((char)('1' + i));
int x = k - 1;
while (temp.size() > 1)
{
int sum = 1;
for (int j = 1; j < n; j++)
sum *= j;
n--;
a = a + temp.get(x / sum);
temp.remove(x / sum);
x = x % sum;
}
a += temp.get(0);
return a;
}
public static void main(String args[])
{
int[] nums = {1,1,2};
//String word = "ABfS";
Solution solution = new Solution();
System.out.print(solution.getPermutation(5, 72));
}
}