lc 第k个排列

链接:https://leetcode-cn.com/problems/permutation-sequence/

代码:

class Solution {
public:
    string getPermutation(int n, int k) {
        int table[11] = {0,1,2,6,24,120,720,5040,40320,362880};
        vector<int> v;
        for(int i = 1; i <= n; i++) {
            v.push_back(i);
        }
        string res = "";
        while(v.size() > 1) {
            int vn = v.size();
            int group = (k-1)/table[vn-1];
            res += to_string(v[group]);
            k -= table[vn-1] * group;
            v.erase(v.begin()+group);
            cout << res << endl;
        }
        cout << v.size() << endl;
        for(int i = 0; i < v.size(); i++) {
            cout << v[i] << endl;
        }
        res += to_string(v[0]);
        return res;
    }
};
View Code

思路:分析数字规律,得出第 K 个排列与n 之间的关系,再不断迭代。

posted on 2020-05-23 00:00  FriskyPuppy  阅读(81)  评论(0编辑  收藏  举报

导航