(92)60. The kth permutation (leetcode)

题目链接:
https://leetcode-cn.com/problems/permutation-sequence/
难度:中等
60. 第k个排列
给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。
按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:
	"123"
	"132"
	"213"
	"231"
	"312"
	"321"
给定 n 和 k,返回第 k 个排列。
说明:
	给定 n 的范围是 [1, 9]。
	给定 k 的范围是[1,  n!]。
示例 1:
	输入: n = 3, k = 3
	输出: "213"
示例 2:
	输入: n = 4, k = 9
	输出: "2314"

Very meow. . . Mathematical method is quite simple to find out the calculation process. My idea is the same as the solution of the problem, but the code written is very different. My code is not very good. The process of understanding the solution is very clear. There is still little contact.

class Solution {
    
    
public:
    vector<int> vec = {
    
     1,1,2,6,24,120,720,5040,40320,362880 };
    string getPermutation(int n, int k) {
    
    
        int curk = k;
        string ans = "";
        vector<string> fla(n);
        for (int i = 0; i < n; ++i) {
    
    
            fla[i] = to_string(i + 1);
        }
        auto it = fla.begin();

        for (int i = 1; i <= n; ++i) {
    
    
            int t = curk / vec[n - i];
            curk = curk % vec[n - i];
            if (!curk) {
    
    
                t--;
            }
            string a = fla[t];
            fla.erase(it + t);
            ans = ans + a;
            if (!curk) {
    
    
                break;
            }
        }
        for (int i = fla.size()-1; i >= 0; --i) {
    
    
            ans += fla[i];
        }
        return ans;
    }
};

This one is clearer

class Solution {
    
    
public:
    vector<int> vec = {
    
     1,1,2,6,24,120,720,5040,40320,362880 };
    string getPermutation(int n, int k) {
    
    
        int curk = k-1;
        string ans = "";
        vector<bool> valid(n + 1, true);

        for (int i = 1; i <= n; ++i) {
    
    
            int t = curk / vec[n - i]+1;
            for(int j=1;j<=n;++j){
    
    
                if(valid[j]){
    
    
                    t--;
                    if(!t){
    
    
                        ans+=(j+'0');
                        valid[j]=false;
                        break;
                    }
                }
            }
            curk = curk % vec[n - i];
        }
        return ans;
    }
};

Thoughts I came up with, nothing better, write it, so it’s time to sleep,,,

Guess you like

Origin blog.csdn.net/li_qw_er/article/details/108414458
Recommended