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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43154149/article/details/108583277