Wednesday, June 4, 2014

Leetcode: 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: 

public class Solution {
    public String getPermutation(int n, int k) {
        ArrayList<Integer> numberPermutations = new ArrayList<Integer>();
        int count = 1;
        numberPermutations.add(1);
        for(int i=1; i<n; i++)
        {
         count*=i;
         numberPermutations.add(count);
        }
        StringBuilder solution = new StringBuilder();
        ArrayList<Integer> used = new ArrayList<Integer>();
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        for(int i=0; i<n; i++)
        {
            numbers.add(i+1);
        }
        count=k-1;
        for(int i=0; i<n; i++)
        {
            int position = count / numberPermutations.get(n-i-1);
            count -= (position * numberPermutations.get(n-i-1));
            solution.append(numbers.get(position));
            numbers.remove(position);
        }
        return solution.toString();
    }
}

No comments :

Post a Comment