[Leetcode] 60. Permutation Sequence 解题报告

介绍两种高效算法来找出从1到n的所有唯一排列中的第k个排列。一种是nextPermutation法,适用于k较小的情况;另一种是迭代法,通常更优,特别是当k远大于n时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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、nextPermutation法:由于我们之前已经实现了nextPermutation,所以只需要先生成一个最小的permutation,然后连续调用k-1次nextPermutation,就可以得到所需要的结果。由于调用nextPermutation的时间复杂度是O(n),所以该思路的时间复杂度是O(n*k),空间复杂度可以做到O(1)(可以直接在string上面做nextPermutation)。此算法仅仅在k <= n的情况下有优势。

2、迭代法:长度为n的字符串的permutation的个数为O(n!),而以任何一个字符开头的permutation共有O((n-1)!)个。通过k值,我们可以首先确定结果字符串中第一个字符;然后更新k值,并且在剩下的字符集合中采取相同的策略确定下一个字符。重复该过程直到n个字符全部被确定。在实现中如果采用vector来表示剩余字符集,则由于每次删除字符集中第k大的字符的时间复杂度高达O(n),所以整个算法的时间复杂度为O(n^2),空间复杂度为O(n)。由于通常情况下 k >> n,所以平均而言思路2比思路1更有优势。(如果有一种数据结构能在最多O(logn)的时间复杂度内完成查找和删除第i大的元素,则该算法的时间复杂度可以进一步降低为O(nlogn),有木有这样的数据结构?)

代码

class Solution {
public:
    string getPermutation(int n, int k) 
    {
        string ret;
        long long factorial = 1;                // the indices
        vector<char> nums(n, '0');              // the letter set
        for(int i = 0; i < n; ++i) 
        {
            factorial *= (i == 0 ? 1 : i);
            nums[i] = '0' + (i + 1);
        }
        k--;                                    // convert to 0-based index
        for(int i = n - 1; i >= 0; --i) 
        {
            int j = k / factorial;              // determine the next letter to be added
            ret.push_back(nums[j]);
            nums.erase(nums.begin()+j);
            k %= factorial;                     // update the index
            if(i > 0)
                factorial /= i;
        }
        return ret;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值