LeetCode(60):Permutation Sequence

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.

题意:求由小于等于n的数字组成的数字,排序之后第k个的值。

思路:参考博文

代码:

public class Solution {
    public String getPermutation(int n, int k) {
       
         int[] permutation = new int[n];
         permutation[0] = 1;
         for(int i=1;i<n;i++){
             permutation[i] = permutation[i-1]*(i+1);
         }
         List<Integer> list = new LinkedList<Integer>();
         for(int i=1;i<=n;i++){
             list.add(i);
         }
         StringBuilder sb = new StringBuilder();
         
        int pos = n-1;
        k-=1;
        while(pos>0){
            int index = k/permutation[pos - 1];
            sb.append(list.get(index));
            list.remove(index);
            k = k%permutation[pos-1];
            --pos;
        }
        sb.append(list.get(0));
        return sb.toString();
    }
}
原文地址:https://www.cnblogs.com/Lewisr/p/5248311.html