Wednesday, April 27, 2016

[LeetCode] 60. 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.



public class Solution {
    public String getPermutation(int n, int k) {
        
        String ret = new String();
        
        if(0 == n)
            return ret;
            
        StringBuilder sb = new StringBuilder();
            
        ArrayList eArr = new ArrayList();
        
        for(int i = 1; i < n+1; ++i){
            eArr.add(i);
        }
        
        int[] pArr = new int[n+1];
        
        pArr[1] = 1;
        
        for(int i = 2; i < n+1; ++i){
            pArr[i] = pArr[i-1]*i;
        }
        
        // Error: i>=0. pArr[0] stored 0. division by 0 error.
        for(int i = n - 1 ; i>=1; --i){
            int pos = (k - 1) / pArr[i];
            sb.append(eArr.get(pos));
            eArr.remove(pos);
            k -= (pos) * pArr[i];
        }
        
        sb.append(eArr.get(0));
        
        return sb.toString();
        
    }
}

No comments:

Post a Comment