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:

思路:根據(jù)排列組合數(shù)量 找位置
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);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 文/歸海無期 也許是晚飯后都市的人行道 無法停止的說話 自顧自地傾倒著回憶 漸漸迷失了自己 也許是落日下河邊的小花...
    歸海無期閱讀 201評(píng)論 0 0
  • 大家都希望自己富有,并且不缺錢花,有的人雖然掙錢很多卻感覺還是資金緊張,而有的人天生的財(cái)運(yùn)好,使自己不缺錢花,從手...
    史蕭楠閱讀 305評(píng)論 0 0
  • 愛情沒有那么多借口,如果愛情不夠圓滿,那一定是愛的不夠。 ――《戀戀筆記...
    山羊家閱讀 181評(píng)論 0 0