码迷,mamicode.com
首页 > 其他好文 > 详细

Permutation Sequence

时间:2014-08-25 22:49:25      阅读:274      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   io   strong   for   div   cti   

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.

思路:使用标准库函数next_permutation循环k-1次求解将会超时。对于最高位n,其取值每加1,对应增加(n-1)!个排列实例。于是,对于给定的k,最高位的取值应为:(k-1) / (n-1)!。因此,可以考虑从高往低逐位确定每一位的取值。

 1 class Solution {
 2 public:
 3     string getPermutation( int n, int k ) {
 4         int factorial = n;
 5         string permutation, selection( n, 1 );
 6         for( int i = 1; i < n; ++i ) {
 7             factorial *= i;
 8             selection[i] += i;
 9         }
10         for( int i = 0; i < n && k > 0; ++i ) {
11             factorial /= (n-i);
12             int select = (k-1) / factorial;
13             k %= factorial;
14             permutation.push_back( selection[select] );
15             selection.erase( select, 1 );
16         }
17         permutation.insert( permutation.end(), selection.rbegin(), selection.rend() );
18         return permutation;
19     }
20 };

 

Permutation Sequence

标签:style   blog   color   使用   io   strong   for   div   cti   

原文地址:http://www.cnblogs.com/moderate-fish/p/3935714.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!