leetcode60. 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.

假設按照題中給的排列組合的順序,假設有1~n個數字,返回第k個排列組合的結果。面試

思路與代碼

首先來整理一下思路。若是有n個數組,則能排列組合出n!個結果。而後再按照排列組合結果的各個位上的數字選擇來分析。這裏舉一個具體的例子。就看題中給的例子,此時n=3。假設k=5。則在百位上,選擇的數字爲[1,2,3]中的第三個,這是再看十位上的數字,選擇了[1,2]中的第一個數。最後在個位上,選擇[1]中的第一個。
能夠總結出,假設輸入n,k,則結果上的從左往右第1位上的數字爲結果集中第(k-1)/(n-1)!個數字。這時知道以第1位爲開頭的結果值有(n-1)!,此時第k個結果集在該位上的選擇爲k%factorial[n-1]。依次日後類推,直至到最後一位。代碼以下:數組

public String getPermutation(int n, int k) {
        //factorial
        int[] factorial = new int[]{1,1,2,6,24,120,720,5040,40320,362880};
        
        //初始化
        List<Integer> numbers = new LinkedList<Integer>();
        for(int i = 0 ; i<n ; i++){
            numbers.add(i+1);
        }
        
        StringBuilder result = new StringBuilder();
        k--;
        for(int i = 0 ; i<n ; i++){
            int currentNumber = numbers.remove(k / factorial[n-i-1]);
            result.append(currentNumber);
            k  %=  factorial[n-i-1] ;
        }
        return result.toString();
    }

clipboard.png
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~微信

相關文章
相關標籤/搜索