首页 > 其他 > 详细

Permutation Sequence

时间:2014-06-04 19:33:14      阅读:426      评论: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,布布扣
class Solution {
private:
    inline int perm(int n)
    {
        int a=1;
        for(int i=1;i<=n;i++)
            a*=i;
        return a;
    }
public:
    string getPermutation(int n, int k) 
    {
        int* num=new int[n];
        for(int i=0;i<n;i++)
            num[i]=i+1;
        int dep=1;
        string s="";
        while(dep<=n)
        {
            int small=1;
            int part=perm(n-dep);
            while(k>part)
            {
                k=k-part;
                small++;
            }
            s=s+char(num[small-1]+0);
            for(int i=small-1;i<n-dep;i++) num[i]=num[i+1];
            dep++;
        }
        return s;
    }
}; 
bubuko.com,布布扣

Permutation Sequence,布布扣,bubuko.com

Permutation Sequence

原文:http://www.cnblogs.com/erictanghu/p/3759434.html

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