Permutation Sequence

来源:互联网 发布:c语言打印日历头文件 编辑:程序博客网 时间:2024/06/10 01:06

Q:

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) {        List<Integer> digits = new ArrayList<Integer>();        for (int i = 1; i <= n; i++)            digits.add(i);        StringBuilder result = new StringBuilder();        for (int i = 0; i < n; i++) {            int product = fac(n-1-i);            int index = 0;            while (k > product) {                k = k - product;                index++;            }            result.append(digits.remove(index));        }        return result.toString();    }        public int fac(int n) {        int ret = 1;        for (int i = n; i > 1; i--)            ret = ret * i;        return ret;    }}


0 0