【记忆化DFS】Leetcode1387. 将整数按权重排序

题目

思路

  • 首先计算出区间内所有权重,最后按照权重排序即可。
  • 计算权重时,如果计算过,那么直接用,如果没计算过,通过状态转移实现递归(如果为偶数,...;如果为奇数,...)

代码(c++)

class Solution {
public:
    // 用于缓存权重的哈希表
    std::unordered_map<int, int> weightCache;

    // 计算权重的函数
    int calculateWeight(int x) {
        if (x == 1) return 0; // 基础条件
        if (weightCache.count(x)) return weightCache[x]; // 如果缓存中存在,直接返回

        // 递归计算权重
        if (x % 2 == 0) {
            weightCache[x] = 1 + calculateWeight(x / 2);
        } else {
            weightCache[x] = 1 + calculateWeight(3 * x + 1);
        }
        return weightCache[x];
    }

    // 主函数
    int getKth(int lo, int hi, int k) {
        std::vector<std::pair<int, int>> numbers;

        // 计算区间内每个数字的权重
        for (int i = lo; i <= hi; ++i) {
            numbers.emplace_back(calculateWeight(i), i);
        }

        // 按权重排序,若权重相同按数字本身排序
        std::sort(numbers.begin(), numbers.end(), [](const std::pair<int, int>& a, const std::pair<int, int>& b) {
            return a.first == b.first ? a.second < b.second : a.first < b.first;
        });

        // 返回排序后第 k 个数字
        return numbers[k - 1].second;
    }
};

结果

End

其实dp应该也可以,dp是正推,通过dp[i]得到dp[2*i],dp[(i-1)/3],而dfs是反推。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rebegin_2023

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值