leetcode | Permutation Sequence

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! 种排列,那么以某一个数开头的排列有 (n1)! 种, 如果 r=k / (n1)! ,则数字 r 位于第一位,然后从数据集中移出数字r 并且 k=k % (n1)! ,依次类推。
另外由
1. “123”
2. “132”
3. “213”
4. “231”
5. “312”
6. “321”
可以观察到只有 k1 才能保证k=1 123;k=2 132同时满足,第1位为1,即 (21)/2!=0 (11)/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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值