首页 > 其他 > 详细

Permutation Sequence

时间:2014-02-06 16:52:48      阅读:314      评论: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.

bubuko.com,布布扣
 1 public class Solution {
 2     public String getPermutation(int n, int k) {
 3         int num[] = new int [n];
 4         int permu = 1;
 5         for(int i=0;i<n;i++){
 6             num[i]=i+1;
 7             permu *= i+1;
 8         }
 9         k--;        
10         StringBuilder sb =new StringBuilder();
11         for(int i=0;i<n;i++){
12             permu /=n-i;
13             int selected = k/permu;
14             sb.append(num[selected]);
15             k %= permu;
16             for(int j=selected+1;j<n;j++){
17                 num[j-1] = num[j];
18             }
19         }
20         return sb.toString();
21     }
22 }
View Code

Permutation Sequence

原文:http://www.cnblogs.com/krunning/p/3538759.html

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