60. Permutation Sequence

https://leetcode.com/problems/permutation-sequence/discuss/22507/%22Explain-like-I'm-five%22-Java-Solution-in-O(n)


https://www.youtube.com/watch?v=xdvPD1IiyUM



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"


// correct, 不是本身寫的
class Solution {
    public String getPermutation(int n, int k) {
        int pos = 0;
        List<Integer> numbers = new ArrayList<>();
        int[] factorial = new int[n + 1];
        StringBuilder sb = new StringBuilder();
        
        // create an array for factorial lookup
        // factorial[] = {1, 1, 2, 6, 24, .. n!}
        int sum = 1;
        factorial[0] = 1;
        for(int i = 1; i <= n; i++){
            sum *= i;
            factorial[i] = sum;
        }
        
        //create a list of numbers to get indices 
        // numbers = {1, 2, 3, 4} 
        for(int i = 1; i <= n; i++){
            numbers.add(i);
        }
        k--;
        for(int i = 1; i <= n; i++){
            int index = k / factorial[ n - i];
            sb.append(Integer.valueOf(numbers.get(index)));
            numbers.remove(index);
            k -= index * factorial[n - i];
        }
        return sb.toString();
        
    }
}
相關文章
相關標籤/搜索