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

[leetcode]Permutation Sequence

时间:2015-07-19 19:21:30      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:

问题叙述性说明:

The set [1,2,3,…,n] contains a total ofn! 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.

基本思想:

依据k和n!之间的关系,第k个序列应该在哪些位置提升几个数字。


代码:

 //consider if k > n! ?  
    string getPermutation(int n, int k) {   //C++
        //the first
        vector<char> base(n,'0'); 
        for(int i = 1; i<=n; i++)
            base[i-1] = i +'0';
        
        vector<int> multi(n);
        int temp = 1;
        multi[0] = 1;
        for(int i =1; i < n; i++){
            temp *= i;
            multi[i] = temp;
        }
        
        k--;
        for(int i = 0; i< n-1; i++){
            int temp = k/multi[n-i-1];
            
            int pos = i+temp;
            char c = base[pos];
            
            for(int j =pos-1 ; j>=i; j-- )
                base[j+1] = base[j];
                
            base[i] = c;
            k = k%multi[n-i-1];
        }
        
        //to String
        string result = "";
        for(int i = 0; i < n; i++)
            result += (base[i]);
        return result;
    }


版权声明:本文博客原创文章,博客,未经同意,不得转载。

[leetcode]Permutation Sequence

标签:

原文地址:http://www.cnblogs.com/gcczhongduan/p/4658949.html

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