LeetCode(60):Permutation Sequence

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
    }
}

以上是关于LeetCode(60):Permutation Sequence的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 60. Permutation Sequence

一天一道LeetCode#60. Permutation Sequence.

Leetcode60 Permutation Sequence

Leetcode 60. Permutation Sequence

leetcode [60] Permutation Sequence

LeetCode60:Permutation Sequence