60. Permutation Sequence (String)

60. Permutation Sequencearrow-up-right

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:

  1. "123"

  2. "132"

  3. "213"

  4. "231"

  5. "312"

  6. "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:

Input: n = 3, k = 3
Output: "213"

Example 2:

Input: n = 4, k = 9
Output: "2314"

My Solutions:

在n! 个permutation中,找出第k个permutation。

第一位数选定后,有(n - 1)!种排列组合

比如1,2,3, 有一个数时,有1种排列;2个数时,有两个排列;3个数时,有6种排列。

可算出对于某个数n,最多有多少排列,用一个int[] sum储存这个值。比如0,1,2,3,sum的值分别是 1, 1, 2, 6。

Time: O(n)

Space: O(n)

Last updated