【Leetcode】Permutation Sequence

来源:互联网 发布:7z解压软件 linux 编辑:程序博客网 时间:2024/04/28 06:50

题目链接:https://leetcode.com/problems/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.

思路:

从左往右计算,先计算最高位。 应该为k/(n-1)! ,下一位应该是(k%(n-1)!)/(n-2)!,以此类推。 

算法:

public String getPermutation(int n, int k) {          int nums[] = new int[n];          int pCount=1;          for(int i=0;i<nums.length;i++){              nums[i] = i+1;              pCount *= (i+1);//n!          }          k--;//下标从0开始          String res = "";          for(int i=0;i<n;i++){              pCount /=n-i;//(n-i-1)!                            int r = k/pCount;              res+=nums[r];//第r小的元素              for(int j=r;j<n-1-i;j++){ //获取第r小的元素 所以将已经用过的元素覆盖                    nums[j] = nums[j+1];              }              k = k%pCount;          }          return res;      }  


1 0
原创粉丝点击