60. Permutation Sequence (String)

60. Permutation Sequence

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。

class Solution {
    public String getPermutation(int n, int k) {
        if (n == 0) return "";
        
        int[] sum = new int[n];
        sum[0] = 1;
        for (int i = 1; i < n; i++) {
            sum[i] = i * sum[i - 1];
        }
        
        StringBuilder sb = new StringBuilder();
        
        k = k - 1; //因为index从0开始
        
        List<Integer> digits = new LinkedList<Integer>();
        //把所有数存在digits里,后面需要用index取用
        for (int i = 1; i <= n; i++) digits.add(i); 
        
        for (int i = n; i > 0; i--) {
            int digit = k / sum[i - 1]; //找到第一位在哪里
            sb.append(digits.get(digit));
            digits.remove(digit); //这个数不能再用了,去掉
            k = k % sum[i - 1]; //k变成在剩下的所有排列中找位置
        }
        
        return sb.toString();
    }
}

Time: O(n)

Space: O(n)

Last updated