leetcode------Permutation Sequence

标题: Permutation Sequence
通过率: 22.7%
难度: 中等

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个是什么,可以这样看

n个数的全排列个数是n!,第一个位置又n种可能,每种可能后的组合是(n-1)!

那么可以先求第一位数。k/(n-1)!,意思如下:

假如n=3,那么开头为1的有2种,2的有两种,3的有两种,如果是求第五个,

那么5/2=2,数组位置2刚好就是3,求完第一个后要把这个位置的前边的可能删除,即求k%fa,余数就是用来求第二位数字

,然后迭代去求,代码如下:

注意list第一位的位置也是0,所以要求的第k位,其实是求第k-1位

代码如下:

 1 public class Solution {
 2     public String getPermutation(int n, int k) {
 3         ArrayList<Integer> num=new ArrayList<Integer>();
 4         int fa=1;
 5         for(int i=1;i<=n;i++){
 6             num.add(i);
 7             fa*=i;
 8         }
 9         k-=1;
10         StringBuilder sb = new StringBuilder();
11         for(int i=n;i>0;i--){
12             fa=fa/i;
13             int index=k/fa;
14             sb.append(num.get(index));
15             num.remove(index);
16             k=k%fa;
17         }
18         return sb.toString();
19     }
20 }
原文地址:https://www.cnblogs.com/pkuYang/p/4361269.html