关闭

leetcode Permutation Sequence

696人阅读 评论(0) 收藏 举报
分类:

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

  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.

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;
  }
};



1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:275678次
    • 积分:4633
    • 等级:
    • 排名:第6531名
    • 原创:152篇
    • 转载:233篇
    • 译文:0篇
    • 评论:6条
    文章分类
    最新评论