LeetCode 刷題記錄 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 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.
Example 1:

Input: n = 3, k = 3
Output: “213”
Example 2:

Input: n = 4, k = 9
Output: “2314”
解法1:
我們可以調用之前寫的下一個排列的函數,循環到第k個函數,但是這種方法不好,我們並需要前邊的排列,只需要第k個排列
解法2:
首先找規律 參考[LeetCode] Permutation Sequence 序列排序
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

class Solution {
public:
    string getPermutation(int n, int k) {
        string res;
        string num = "123456789";
        vector<int> f(n,1);
        for(int i = 1; i < n; i++){
            f[i] = f[i-1] * i;
        }
        --k;
        for(int i = n-1; i >= 0; i--){
            int j = k / f[i];
            k = k % f[i];
            res.push_back(num[j]);
            num.erase(j,1);
        }
        return res;
    }
};

java:
java中String是不可變對象,沒有去除某個位置字符的方法,所以與c++不同,我們採用List num = new ArrayList()來存num,同時我們用StringBuilder res來存目標字符串更加高效

class Solution {
    public String getPermutation(int n, int k) {
        StringBuilder res = new StringBuilder();
        List<Integer> num = new ArrayList<Integer>();
        int[] f = new int[n];
        f[0] = 1;
        for(int i = 1; i < n; i++){
            f[i] = f[i-1] * i;
            num.add(i);
        }
        num.add(n);
        --k;
        for(int i = n-1; i >= 0; i--){
            int j = k / f[i];
            k = k % f[i];
            res.append(num.get(j));
            num.remove(j);
        }
        return res.toString();
    }
}

python:
python可以用divmod函數同時獲取除數和餘數,同時用math.factorial(n)獲取n的階乘
注意java中ArrayList中remove函數傳的是下標,但是python 列表中remove函數傳的是值,如果用下標的話用pop函數
在這裏插入圖片描述
在這裏插入圖片描述

class Solution(object):
    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        res = ""
        num = range(1,n+1)
        
        k -= 1
        n -= 1
        
        while n >= 0:
            index, k = divmod(k, math.factorial(n))
            res += str(num[index])
            num.remove(num[index])
            n -= 1
            
        return res
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章