LCP 20. 快速公交 || 1553. 吃掉 N 个橘子的最少天数【记忆化递归】

LCP 20. 快速公交

启示:在记忆化搜索过程中,可以用一个哈希表存中间结果,记忆化的精髓!

typedef long long LL;
const int mod = 1e9+7;
class Solution {
public:
    unordered_map<LL,LL> table;
    int busRapidTransit(int target, int inc, int dec, vector<int>& jump, vector<int>& cost) {
        table.clear();
        return dfs(target,inc,dec,jump,cost)%mod;
    }

    LL dfs(int target,int inc, int dec, vector<int>& jump, vector<int>& cost){
        if(!target) return 0;  //如果当前在起点,花费为0
        if(target == 1) return inc; // 距离为1,直接走,不能再坐车了,不然死循环
        if(table[target]) return table[target];

        LL res = (LL)target*inc;  //直接从target一步一步走到起点的花费
        for(int i = 0; i<jump.size(); i++){
           int u = target / jump[i], v = target % jump[i];
           if(v == 0){
               res = min(res,dfs(u,inc,dec,jump,cost) + cost[i]);
           }else{
               res = min(res,dfs(u,inc,dec,jump,cost) + cost[i] + (LL)v * inc); // (LL)v * inc这里要加LL,不然溢出
               res = min(res,dfs(u + 1,inc,dec,jump,cost) + cost[i] + (LL)(jump[i] - v) * dec);
           }
        }
        table[target] = res;  //保存一些计算过的中间变量
        return res;
    }
};

1553. 吃掉 N 个橘子的最少天数

class Solution {
public:
    unordered_map<int,int> table;
    int minDays(int n) {
        return dfs(n);
    }

    int dfs(int n)
    {
        if(n == 0) return 0;
        if(n == 1) return 1;
        if(n == 2) return 2; // 不加这句话会爆栈,原因dfs(2 % 3) 还是等于2一直循环,直接返回
        if(table[n]) return table[n];

        int res = n;
        // 还有余数部分
        res = min(res,1 + dfs(n / 3) + dfs(n % 3));
        res = min(res,1 + dfs(n / 2) + dfs(n % 2));
        
        table[n] = res;
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值