Friday, May 1, 2015

[LeetCode] Permutation Sequence

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 kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
Solution: From left to right, we compute each digit in the desired sequence.
Some simple observations:
1. If k denotes the last sequence, construct the last sequence and return;
2. Compute the highest digit, and update k. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Solution {
    public String getPermutation(int n, int k) {
        int[] factorial = new int[n];
        factorial[0] = 1;
        for (int i = 1; i < n; i++) {
            factorial[i] = factorial[i - 1] * (i + 1);
        }
        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i = 1; i <= n; i++) {
            list.add(i);
        }
        StringBuffer sb = new StringBuffer();
        int m = n - 1;
        while (k > 0) {
            if (k == factorial[m]) {
                for (int i = list.size() - 1; i >= 0; i--) {
                    sb.append(list.get(i));
                }
                return sb.toString();
            } else {
                int t = (k - 1) / factorial[m - 1];
                sb.append(list.remove(t));
                k = k - t * factorial[m - 1];
                m--;
            }
        }
        return sb.toString();
    }
}

No comments:

Post a Comment