60. 第k個排列

數學規律

難度:中等
推薦視頻:米開

版本1【數學規律】

class Solution {
public:
    string getPermutation(int n, int k) {
        //2020.2.28 評論題解 數學規律
        string temp = "123456789";
        string res;
        vector<int> f(10); //階乘結果
        f[0] = 1;
        for(int i = 1; i <= 9; i ++) f[i] = f[i-1]*i;
        k--; //從0開始編號
        while(n > 0){
            int index = k/f[n-1];
            res += temp[index];
            temp.erase(temp.begin()+index); //刪除 挪位
            k %= f[n-1];
            n--;
        }
        return res;
    }
};

版本2【DFS+剪枝】

class Solution {
public:
    string res;
    vector<bool> st;
    int n, cnt = 0;
    string getPermutation(int _n, int k) {
        n = _n;
        st.resize(n+1);
        dfs("", k, 0);
        return res;
    }
    bool dfs(string temp, int &k, int u){
        if(u == n){
            cnt++;
            if(k == cnt){
                res = temp;
                return true;
            }
            return false;
        }
        for(int i = 1; i <= n; i++){
            if(!st[i]) {
                st[i] = true;
                if(dfs(temp+char(i+'0'), k, u+1)) return true;
                st[i] = false;
            }
        }
        return false;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章