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 (ie, for $n = 3$):

1."123"

2."132"

3."213"

4."231"

5."312"

6."321"

Given $n$ and $k$, return the $k^{th}$ permutation sequence.

Note: Given $n$ will be between 1 and 9 inclusive.

Solution:

public class Solution {
    public String getPermutation(int n, int k) {
        List<Integer> digits = new ArrayList<>();
        int factorial = 1;
        for(int i=1; i<=n; i++){
            digits.add(i);
            factorial *= i;
        }
        int num = 0;
        k--; /* adapt to zero based counting */
        for(int i=n; i>=1; i--){
            factorial /= i;
            num = 10*num + digits.get(k/factorial);
            digits.remove(k/factorial);
            k %= factorial;
        }
        return String.valueOf(num);
    }
}
comments powered by Disqus