60. 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):
"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.

Solution:

思路:根据排列组合数量 找位置
Time Complexity: O(N) Space Complexity: O(N)

Solution Code:

public class Solution {
    public String getPermutation(int n, int k) {
        int pos = 0;
        List<Integer> numbers = new ArrayList<>();
        int[] factorial = new int[n+1];
        StringBuilder sb = new StringBuilder();

        // create an array of factorial lookup
        int sum = 1;
        factorial[0] = 1;
        for(int i=1; i<=n; i++){
            sum *= i;
            factorial[i] = sum;
        }
        // factorial[] = {1, 1, 2, 6, 24, ... n!}

        // create a list of numbers to get indices
        for(int i=1; i<=n; i++){
            numbers.add(i);
        }
        // numbers = {1, 2, 3, 4}

        k--;

        for(int i = 1; i <= n; i++){
            int index = k/factorial[n-i];
            sb.append(String.valueOf(numbers.get(index)));
            numbers.remove(index);
            k-=index*factorial[n-i];
        }

        return String.valueOf(sb);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 文/归海无期 也许是晚饭后都市的人行道 无法停止的说话 自顾自地倾倒着回忆 渐渐迷失了自己 也许是落日下河边的小花...
    归海无期阅读 201评论 0 0
  • 大家都希望自己富有,并且不缺钱花,有的人虽然挣钱很多却感觉还是资金紧张,而有的人天生的财运好,使自己不缺钱花,从手...
    史萧楠阅读 311评论 0 0
  • 爱情没有那么多借口,如果爱情不够圆满,那一定是爱的不够。 ――《恋恋笔记...
    山羊家阅读 182评论 0 0