Permutation Sequence

来源:互联网 发布:linux telent 安装 编辑:程序博客网 时间:2024/05/27 20:50

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.

Show Tags

Have you met this question in a real interview?

思路: 这个排列是按照 (n - 1) ! 来排列的, 每一层都有( n - 1 ) ! 个 数字, 因此我们要找到是第 selectI 个 要先 除以 (n - 1) !, 然后找到在没使用的数字中 的 第  selectI 个 数字, 并设置为已经使用。 最后如果 到了 第1 个,把剩余的没使用的数字按顺序插入。

易错点:  1 .  k 一开始要  减1 。

2. level  每次 要除以 n - i ;   i  从1 到 n - 1

public class Solution {    public String getPermutation(int n, int k) {boolean[] used = new boolean[n + 1];StringBuilder buffer = new StringBuilder();used[0] = true;int level = 1;for (int i = 1; i < n; ++i) {level *= i;// 阶乘的当前level }k = k - 1;//-----非常重要for (int i = 1; i < n; ++i) {int selectI = k / level;for(int j = 1; j <= n; j++){if(!used[j]){selectI--;}if(selectI == -1){used[j] = true;buffer.append(j);break;}}k = k % level;//-----level /= (n - i);//--- 从 n - 1 , 除到 1, 阶乘 反向除下去}for(int i = 1; i <= n; i++){// 把还没用过的数字按顺序 插入if(!used[i]){    used[i] = true;buffer.append(i);break;}}return new String(buffer);}}


0 0
原创粉丝点击