60. Permutation Sequence

来源:互联网 发布:研如寓 知乎 编辑:程序博客网 时间:2024/06/05 20:34

String ret = "";    int k;    public String getPermutation(int n, int k) {        this.k = k - 1;//第k个字符串表示变化了k - 1次        int[] alphabet = new int[n];//存储还有哪些数字可选        for (int i = 1;i <= n;i++)//初始化数字表            alphabet[i - 1] = i;        recursive(alphabet,n);        return ret;    }    public void recursive(int[] alphabet,int n){//n表示正在计算第n位的值        if (n == 0) return;//递归必须设置结束点        int factorial = factorial(n - 1);        int quotient = k / factorial;//求出商看它在倒数第i位变了几次        k %= factorial;        ret += String.valueOf(alphabet[quotient]);        int[] newAlphabet = new int[n - 1];        for (int i = 0,j = 0;i < n;i++)//生成新的数字表,不包含原数字表里已经用过的数字            if (i != quotient) {                newAlphabet[j] = alphabet[i];                j++;            }        recursive(newAlphabet,n - 1);    }    public int factorial(int x){//求阶乘的函数        if (x == 0) return 1;        int factorial = x;        while (x > 1){            factorial *= --x;        }        return factorial;    }

原题:

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.

即给定int n,int k。返回第k个n的全排列(按递增形式排列)所形成的数字串。


思考过程:

一开始意识到这个和阶乘相关,但是思路并不清晰。后来意识到比如n = 5,k = 120,是从12345往上变化了119次。变化4! * 4次后是51234,也就是从右往左数的第n为取决于

k / (n - 1)!,其中k每次都更新为k % (n - 1)!。采用递归的算法,用一个数组存储还剩下的数字(递增顺序),然后每次递归更新k值和字母表。详情见代码注释。


AC代码:

原创粉丝点击