Thursday, January 8, 2015

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) {
        // http://www.cnblogs.com/tenosdoit/p/3721918.html
        List<String> num = new LinkedList<>();
        int perm = 1; // n!
        
        for (int i = 0; i < n; i++)
        {
            num.add(String.valueOf(i+1));
            perm *= i+1;
        }
        
        String result = "";
        k--; // Changed to 0-based
        
        for (int i = 0; i < n; i++)
        {
            perm /= n-i;
            
            int index = k/perm;
            String val = num.remove(index); // Delete the selected number and recontruct the 'num' list
            
            result += val;
            k = k%perm;
        }
        
        return result;
    }
}

No comments:

Post a Comment