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

Permutation Sequence

时间:2014-06-04 19:56:17      阅读:347      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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

标签:c   style   class   blog   code   java   

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

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