Permutation Sequence

The set[1,2,3,…,n]contains a total ofn! unique permutations.

By listing and labeling all of the permutations in order,
We get the following sequence (ie, forn= 3):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Givennandk, return thekthpermutation sequence.

public class Solution {
    public String getPermutation(int n, int k) {

        int[] f = new int[n + 1];

        f[0] = 1;
        for(int i = 1; i <=n; i ++) {
            f[i] = f[i-1] * i;
        }

        List<String> seq = new ArrayList<>();
        for(int i = 1; i <= n; i ++){
            seq.add(i+"");
        }

        k --;
        StringBuilder res = new StringBuilder();
        for(int i = 1; i <= n; i ++) {
            int index = k / f[n - i];
            res.append(seq.get(index));
            seq.remove(index);
            k %= f[n - i];
        }

        return res.toString();

    }
}

results matching ""

    No results matching ""