您的位置:首页 > 产品设计 > UI/UE

leetcode Permutation Sequence

2013-12-03 20:26 465 查看


Permutation Sequence

Total Accepted: 1819 Total
Submissions: 9060My Submissions

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):

"123"

"132"

"213"

"231"

"312"

"321"


Given n and k, return the kth permutation
sequence.
Note: Given n will be between 1 and 9 inclusive.

Discuss

Three problems:

1. overly dependent on next_permutation, TLE

2. --k. If k%a! == b, so the bth character should be brought forward from the rear a elements.

3. If the length is n, n - 1 adjustments are enough. So i = n instead of n - 1

for (i = n - 1; i >= 1; --i) {


class Solution {
 public:
  int factorial[10];
  string getPermutation(int n, int k) {
    string res = "";
    int i, j, tmp;
    vector<int> pos;
    factorial[0] = 1;
    for (i = 1; i <= n; ++i) {
      factorial[i] = factorial[i - 1] * i;
      res.push_back('0' + i);
    }
    --k;
    for (i = n - 1; i >= 1; --i) {
      pos.push_back(k / factorial[i]);
      k = k % factorial[i];
    }
    for (i = 0; i < pos.size(); ++i) {
      tmp = res[i + pos[i]];
      for (j = pos[i]; j >= 1; --j)
        res[i + j] = res[i + j - 1];
      res[i] = tmp;
    }
    
    return res;
  }
};

Give a WA code here, find the bug:

class Solution {
 public:
  string getPermutation(int n, int k) {
    vector<int> factorial(n, 1);
    string res(n, '1');
    for (int i = 1; i < n; ++i) {
      factorial[i] = factorial[i-1]*i;
      res[i] += i - 1;
    }
    --k;
    for (int i = 0; i < n; ++i) {
      int tmp = k / factorial[n - 1 - i];
      char ch = res[i + tmp];
      for (int j = tmp + i; j > i; --j)
        res[j] = res[j - 1];
      res[i] = ch;
      k = k % factorial[n - 1 - i];
    }
    return res;
  }
};


Another AC version:

class Solution {
 public:
  string getPermutation(int n, int k) {
    vector<int> factorial(n, 1);
    string res(n, '1');
    for (int i = 1; i < n; ++i) {
      factorial[i] = factorial[i-1]*i;
      res[i] += i;
    }
    --k;
    for (int i = 0; i < n; ++i) {
      int tmp = k / factorial[n - 1 - i];
      char ch = res[i + tmp];
      for (int j = tmp + i; j > i; --j)
        res[j] = res[j - 1];
      res[i] = ch;
      k = k % factorial[n - 1 - i];
    }
    return res;
  }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: