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

60 Permutation Sequence

时间:2015-07-01 18:33:55      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:leetcode

60 Permutation Sequence

链接:https://leetcode.com/problems/permutation-sequence/
问题描述:
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.

Hide Tags Backtracking Math

给定一个0-9的n和数字k,求第k个序列。在给出的例子中可以看出,排列的顺序是从数字小到大。从这里入手我们可以发现一些规律:

1 由于计算机中技术都是从0开始,我先做的操作是让k–,下一步可以看出这样做的好处。建立数组int flag[9]={0,0,0,0,0,0,0,0,0},这个数组保证每个数字只会出现一次,当一个数字使用时置1。flag[0]=1表示数字1已经使用。

2 看第一个数字num1该怎么取,num1=k/(n-1)!,flag[num1]更新为1。这里需要注意的是num1真正的意义更像是一个索引,下一步会有介绍。如果没有做k–,那么num1=k/(n-1)!就会出现问题,比如n=3,k=2的时候。

3 更新k=k%(n-1)!;

4 第二个数字num2=k/(n-2)!。但是这里出现的问题是,num2并不是我们真正需要的数字,比如开始输入n=3,k=4。num1=1,num2=1;这里需要明白我们求得num1,num2,num3……实际代表的意义当前所有未用到的数字从小到大排列的第num个,所以我们求出的num更像是一个索引。再来看开始输入n=3,k=4这个例子,num1=1,num2=1,第一步取出的数字是2,还剩下1,3,那么num2=1所对应的数字就是3,排序都是从0开始。

5循环这个过程,直到最后一步,是剩下一个数字可以选。

class Solution {
public:
    string getPermutation(int n, int k) 
    {
        string result="";
        int arr[9]={1,1,2,6,24,120,720,5040,40320},key=1;
        int flag[9]={0,0,0,0,0,0,0,0,0};
        k--;
        for(int i=0;i<n;i++)
       {
           key=k/arr[n-1-i];
           int j=0;
           for(;key>0||flag[j]!=0;j++)
           {
               if(flag[j]==0)
                   key--;
           }

            flag[j]=1;
            result+=j+‘1‘;

         k=k%arr[n-1-i];
       }
       return result;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

60 Permutation Sequence

标签:leetcode

原文地址:http://blog.csdn.net/efergrehbtrj/article/details/46710721

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