首页 > 其他 > 详细

【Leetcode】Permutation Sequence

时间:2014-03-18 16:43:57      阅读:377      评论:0      收藏:0      [点我收藏+]

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.

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     string getPermutation(int n, int k) {
 4         string result;
 5         bool used[10];
 6         memset(used, false, 10);
 7         int base[10];
 8         base[1] = 1;
 9         for (int i = 2; i <= n; ++i) {
10             base[i] = base[i - 1] * i;
11         }
12         --k;
13         for (int i = 0; i < n; ++i) {
14             int p = k / base[n - 1 - i];
15             for (int j = 1; j <= n; ++j) {
16                 if (!used[j] && p-- == 0) {
17                     result.push_back(0 + j);
18                     used[j] = true;
19                     break;
20                 }
21             }
22             k %= base[n - 1 - i];
23         }
24         return result;
25     }
26 };
View Code

n个数组的全排列中,以1开头的个数(n-1)!个,同样以2..n开头的个数有(n-1)!个,这样根据(k-1)/[(n-1)!]可知第一个数是多少,依次类推...

【Leetcode】Permutation Sequence,布布扣,bubuko.com

【Leetcode】Permutation Sequence

原文:http://www.cnblogs.com/dengeven/p/3607992.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!