首页 > 其他 > 详细

Permutation Sequence

时间:2014-04-05 10:44:50      阅读:501      评论: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):
"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.

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     // case n = 3, k = 2 (k starts from 1)
 4     string getPermutation(int n, int k) {
 5         string s;
 6         int total = 1;
 7         for(int i = 1; i <= n; i++) {
 8             s.push_back(i+‘0‘); // s="123";
 9             total *= i; // total = 1x2x3
10         }
11         k--;
12         string res;
13         while(n) {
14             total /= n;
15             int i = k / total;
16             res.push_back(s[i]);
17             s.erase(i,1);
18             k %= total;
19             n--;
20         }
21         return res;
22     }
23 };
bubuko.com,布布扣

 

Permutation Sequence,布布扣,bubuko.com

Permutation Sequence

原文:http://www.cnblogs.com/zhengjiankang/p/3646368.html

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