LeetCode *** 60. Permutation Sequence

来源:互联网 发布:linux sleep longer 编辑:程序博客网 时间:2024/05/01 18:38

题目:

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 {public:string getPermutation(int n, int k) {string res = "";bool *candi=new bool[n];for (int i = 0; i < n; ++i)candi[i] = false;int total = 1, pos = 1, tk = k-1;while (pos<n) {total *= pos;pos++;}pos--;while (tk&&pos) {int t = tk / total+1;int i=0, j=0;while (i < t&&j<n) {if (!candi[j])i++;j++;}res += ('0' + j);candi[j - 1] = true;tk = tk%total;total /= pos;pos--;}for (int i = 0; i<n; ++i) {if (!candi[i])res += ('0' + i + 1);}return res;}};

0 0
原创粉丝点击