leetcode 日经贴,Cpp code -Permutation Sequence

来源:互联网 发布:淘宝上传不了图片 编辑:程序博客网 时间:2024/05/24 01:04

Permutation Sequence

class Solution {public:    string getPermutation(int n, int k) {        string s = "";        vector<int> fact;        fact.resize(n + 1);        fact[0] = 1;        for (int i = 0; i < n; ++i) {            s += char('1' + i);            fact[i + 1] = fact[i] * (i + 1);        }        --k;        for (int i = 0; i < n && k > 0; ++i) {            int f = fact[n - i - 1];            int pos = k / f;            k %= f;            if (pos > 0) {                char ch = s[pos + i];                for (int j = pos; j > 0; --j) {                    s[j + i] = s[j + i - 1];                }                s[i] = ch;            }        }        return s;    }};


0 0