首页 > 其他 > 详细

Permutation Sequence -- leetcode

时间:2015-04-01 15:21:24      阅读:264      评论: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) {
        vector<char> pers(n, '1');
        int fact = n;
        for (int i=1; i<n; i++) {
            fact *= i;
            pers[i] = '1' + i;
        }
        
        k--;
        string ans;
        for (int i=0; i<n; i++) {
            fact /= (n-i);
            const int j = k / fact;
            k %= fact;
            
            ans.push_back(pers[j]);
            pers.erase(pers.begin()+j);
        }
        
        return ans;
    }
};

在leetcode上,实际执行时间为5ms。

基本思路:

参照普通进制的方法,求出每位的权重,从高位到低位利用整除和取余求出每位的值。

区别为,此权重都是阶乘值,不像普通进制,为基数的各次幂。

Permutation Sequence -- leetcode

原文:http://blog.csdn.net/elton_xiao/article/details/44807001

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