美文网首页
Leetcode60-Permutation Sequence

Leetcode60-Permutation Sequence

作者: BlueSkyBlue | 来源:发表于2018-05-19 22:46 被阅读4次

    题目:

    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 for n = 3:

    "123"
    "132"
    "213"
    "231"
    "312"
    "321"
    Given n and k, return the kth permutation sequence.

    Note:

    Given n will be between 1 and 9 inclusive.
    Given k will be between 1 and n! inclusive.

    Example1
    Input: n = 3, k = 3
    Output: "213"

    Example2
    Input: n = 4, k = 9
    Output: "2314"


    思路:

    假设n是3,k是2。咱们首先需要找第一个数。咱们首先观察n为3时的各个字符串的排序:
    123
    132
    213
    231
    312
    321
    可以观察到1,2,3后面各有两个排列,当第一个数为1的时候,它后面的是2,3的全排列,第一个数是2,3的时候也是这样的情况。也就是说它的全排列是1+(2,3的全排列),2+(1,3的全排列),3+(1,2的全排列)。(2,3),(1,3)或者(1,2)的全排列为2!。所以要找到排在第二位的字符串的首字母的参数需要使用2/2!来计算。也就是第n个数的首字母的参数是n/(n-1)!。

    这里需要一个数组或者队列存储[1, n]的所有数据。计算出来的参数需要从这个数组中取数据。取出数据后需要把该数组或者队列这个位置上的数据删掉。因为最后的结果中不能存在同样的字符。同时n也要变化变为n%(n-1)!。此时的n代表着在n-1数中排名第n位的字符串。查找如上同样的办法,只是由于首字母咱们已经找到了这个时候除数应当变为(n-2)!

    Note:公式中的n是题目一开始给的n。

    之后在依次循环下去,直到循环到n位。因为最终的结果就是n位字符。


    代码:

    public String Solution(int n, int rank){
            StringBuilder sb = new StringBuilder();
            ArrayList<Integer>res = new ArrayList<Integer>();
            int [] fact = new int[n];
            fact[0] = 1;
            for(int i=1;i<n;i++){
                fact[i] = i * fact[i-1];
            }
            for(int i=0;i<n;i++)
                res.add(i+1);
            rank = rank - 1;
            for(int i=n;i>0;i--){
                int index = rank / fact[i-1];
                rank = rank % fact[i-1];
                sb.append(res.get(index));
                res.remove(index);
            }
            return sb.toString();
    }
    

    相关文章

      网友评论

          本文标题:Leetcode60-Permutation Sequence

          本文链接:https://www.haomeiwen.com/subject/qlaadftx.html