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

Permutation Sequence -- leetcode

时间:2015-04-01 15:22:03      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:leetcode   permutation   排列   

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

标签:leetcode   permutation   排列   

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

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