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

leetcode | Permutation Sequence

时间:2015-05-30 16:44:50      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:sequence   array   leetcode   

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.


解析

1. 调用 next Permutation

调用上一题Next Permutation中的函数,逐步计算下一个队列,直到第k个。(暴力枚举)

    string getPermutation(int n, int k) {
        string result;
        vector<int> nums;
        for (int i = 1; i <= n; i++)
            nums.push_back(i);  //初始化第一个排列
        for (int j = 1; j < k; j++)
            nextPermutation(nums);  //计算第k个排列
        for (int k = 0; k < n; k++)
            result.push_back(nums[k]); 
        return result;
    }

做了很多无用功,因为我们只需得到第 k 个排列,上述算法计算了所有排列,耗时太大,不能满足要求。

2. 数学解法

[1,2,3,…,n] 包含了 n! 种排列,那么以某一个数开头的排列有(n?1)!种, 如果 r=k / (n?1)!,则数字r位于第一位,然后从数据集中移出数字r 并且 k=k % (n?1)!,依次类推。
另外由
1. “123”
2. “132”
3. “213”
4. “231”
5. “312”
6. “321”
可以观察到只有k?1才能保证k=1 123;k=2 132同时满足,第1位为1,即(2?1)/2!=0(1?1)/2!=0

class Solution {
public:
    string getPermutation(int n, int k) {
        string result;
        vector<int> set; 
        for (int i = 1; i <= n; i++)
            set.push_back(i);
        k--;  //k-1后才能应用于整除
        int count = factorial(n);  // n! 组合数
        for (int j = n; j > 0; j--) {
            count = count / j;  // (j-1)!
            int r = k / count;
            result.push_back(set[r]+‘0‘);
            set.erase(set.begin()+r);  //移除set[r],或将r后的元素整体前移一位
            k = k % count;
        }
        return result;
    }

 private:
    int factorial(int n) {  //求阶乘
        if (n == 0)
            return 1;
        int result = 1;
        while (n) {
            result *= n;
            n--;
        }
        return result;
    }
};

leetcode | Permutation Sequence

标签:sequence   array   leetcode   

原文地址:http://blog.csdn.net/quzhongxin/article/details/46275003

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