2014年3月16日星期日

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.


public class Solution {
    public String getPermutation(int n, int k) {
        int num[] = new int[n];
        int count = 1;
        for(int i=0;i<n;i++) {
            num[i] = i+1;
            count *= num[i];
        }
        k -= 1;
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<n;i++) {
            count /= (n-i);
            int sel = k/count;
            sb.append(num[sel]);
            k = k%count;
            for(int j=sel;j<num.length-1;j++) {
                num[j] = num[j+1];
            }
        }
        return sb.toString();
    }
}

============

public class Solution {
    public String getPermutation(int n, int k) {
        int count = 1;
        List<Integer> arr = new ArrayList<Integer>();
        for (int i = 1; i <= n; i++) {
            count *= i;
            arr.add(i);
        }
        StringBuilder sb = new StringBuilder();
        k = k - 1;
        while (n > 0) {
            count /= n;
            int id = k /count;
            sb.append(arr.get(id));
            arr.remove(id);
            k = k % count;
            n--;
        }  
        return sb.toString();
    }
}

没有评论:

发表评论