每日一题 2019 - 04 - 03
题目:
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 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.
- Given k will be between 1 and n! inclusive.
Example 1:
1 | Input: n = 3, k = 3 |
Example 2:
1 | Input: n = 4, k = 9 |
思路:
这个题让我们找到给定序列全拍列的第 K
个序列是什么;
常规思路就是写个全排列,找到第 K
个,可是这个题运用全排列算法会超时;
所以需要换个思路:
1)第k个排列的第一个元素在0-n中的位置为(k-1)/(n-1)!
2)在剩下的元素中继续找第一个;
3)依此类推;
代码:
1 | class Solution { //最高位等于k/(factorial(n-i))-1 |