leetcode 60. Permutation Sequence

来源:互联网 发布:淘宝客服差评处理技巧 编辑:程序博客网 时间:2024/05/01 19:58

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 (ie, for n = 3):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.



class Solution {set<string>re;void select_one(vector<pair<string, vector<int>>>&candis){vector<pair<string, vector<int>>>newcandi;re.clear();for (int i = 0; i < candis.size(); i++){for (int j = 0; j < candis[i].second.size(); j++){string pp = candis[i].first;pp += '0' + candis[i].second[j];if (candis[i].second.size() == 1)re.insert(pp);else{vector<int>remain = candis[i].second;remain.erase(remain.begin() + j, remain.begin() + j + 1);newcandi.push_back(pair<string, vector<int>>(pp, remain));}}}candis = newcandi;}public:string getPermutation(int n, int k) {vector<int>nums;for (int i = 0; i < n; i++)nums.push_back(i + 1);int jj = n;vector<pair<string, vector<int>>>candi;candi.push_back(pair<string, vector<int>>(string(""), nums));while (jj-- >= 1){select_one(candi);}int i = 1;for (set<string>::iterator it = re.begin(); it != re.end(); it++, i++)if (i == k)return *it;}};

试试9,慢的吓人,坑定不能用这种方法。

换一种方法


class Solution {long long int factorial(int n){long long int re = 1;for (int i = 1; i <= n; i++)re *= i;return re;}public:string getPermutation(int n, int k) {if (n == 1 && k == 1)return string("1");vector<int>nums;for (int i = 0; i < n; i++)nums.push_back(i + 1);int jj = n;string re;while (true){int index = (k-1) / (factorial(jj - 1));k = k-factorial(jj - 1)*index;re += '0' + nums[index];nums.erase(nums.begin()+index, nums.begin()+index+1);jj--;if (jj == 1){re += ('0' + nums[0]);return re;}}}};


accepted



0 0
原创粉丝点击