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

leetcode[60]Permutation Sequence

时间:2015-02-09 15:34:37      阅读:189      评论: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.

class Solution {
public:
string getPermutation(int n, int k) 
{
    k--;
    string str="";
    int data[10]={1};
    int flag[10]={0};
    for (int i=1;i<=n;i++)
    {
        data[i]=data[i-1]*i;
    }
    for (int i=n-1;i>=0;i--)
    {
        int k1=k/data[i];
        int k2=k%data[i];
        k1++;
        int jj=0;
        for (int j=0;j<n;j++)
        {
            if (flag[j]==0)
            {
                jj++;
                if (jj==k1)
                {
                    char temp=0+(j+1);
                    str+=temp;
                    flag[j]=1;
                    break;
                }
            }
        }
        k=k2;
    }
    return str;
}
};

 

leetcode[60]Permutation Sequence

标签:

原文地址:http://www.cnblogs.com/Vae98Scilence/p/4281521.html

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