Permutation Sequence
https://leetcode.com/problems/permutation-sequence/description/
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, forn= 3):
"123"
"132"
"213"
"231"
"312"
"321"
Givennandk, return thekthpermutation sequence.
Thoughts
把首位固定, 那每组会有(N-1)!个数. 我们让k/(N - 1)!就可以知道kth的第一个数是多少. 这时我们要把第一个数从nums中移出去, 更新k = k % (N - 1)!. 同理判断第二个数的index是多少. 依次类推下去.
Code
Analysis
Errors: 1. k在运算前必须-1. 时空复杂度为O(N).
Last updated
Was this helpful?