leetcode记录60.Permutation Sequence

本文介绍了一个高效的算法解决LeetCode上的第60题“排列序列”,该算法在200个测试用例中全部通过,运行时间为4ms,击败了66.46%的C++提交,在内存使用上也表现优秀,击败了73.68%的C++提交,使用了回溯法来找到第k个排列。

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

leetcode记录60.Permutation Sequence

√ Accepted
  √ 200/200 cases passed (4 ms)
  √ Your runtime beats 66.46 % of cpp submissions
  √ Your memory usage beats 73.68 % of cpp submissions (8.3 MB)


class Solution {
public:
    string getPermutation(int n, int k) {
        string result = "";
        string v = "";
        for (int i = 0; i < n; i++)
        {
            char c = '0' + i + 1;
            v = v + c; 
        }
        bt(k, result, v);
        return result;
    }

    void bt(int k, string & result, string v)
    {
        int count = 1;
        int num = v.size();
        while (result.size() < num)
        {
            int n = v.size();
            for (int i = 1; i <= n; i++)
            { 
                if (count * i >= k)
                {
                    if(count * i == k)
                    {   
                        for (int j = 1; j <= n; j++)
                        {
                            if(j <= n-i)
                            {
                                result = result + v[j-1];
                            }
                            else
                            {
                                result = result + v[2*n-i-j];
                            }   
                        }
                        break;
                    }
                    int temp = (k-1) / count;
                    k = (k-1) % count + 1;
                    for (int j = 1; j <= n - i; j++)
                    {
                        result = result + v[j-1];
                    }
                    v = v.substr(n-i);
                    result = result + v[temp];
                    v.erase(temp, 1);
                    break;
                    
                }
                else
                {
                    count *= i;
                }  
            }
            count = 1;
        }
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值