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"

time o(n), space o(n)

class Solution {
    public String getPermutation(int n, int k) {
        List<Integer> list = new ArrayList<>();
        for(int i = 1; i <= n;i++){
            list.add(i);
        }
        
        int[] factor = new int[n];
        
        factor[0] = 1;
        
        
        // 后面 k / (n-1)!,所以这里不需要n!
        for(int i = 1; i <n; i++){
            factor[i] = i*factor[i-1];
        }
        
        k = k-1;
        StringBuilder sb = new StringBuilder();
        
        
        for(int i = n; i > 0; i--){
            int index = k / factor[i-1];
              k = k % factor[i-1];
            sb.append(list.get(index));
            //全排列,这个数用过了就不能再用了
            list.remove(index);
        }
        
        return sb.toString();
    }
}

Last updated