路径规划07

路径规划07

1575. 统计所有可行路径

今天又是一道hard呢,加油干碎它,干碎这道题就进入进阶部分了

先从记忆化搜索开始(因为普通dfs会超时)

普通dfs步骤:

1.递归函数的入参和出参确定

2.递归出口 Base Case

3.编写最小单元的逻辑

通常Base Case 是最难的部分

class Solution {
public:
    int mod=1000000007;
    int cache[201][201];
    int countRoutes(vector<int>& locations, int start, int finish, int fuel) {
        int n=locations.size();
        memset(cache,-1,sizeof(cache));
        return dfs(locations,start,finish,fuel);
    }
    

    int dfs(vector<int>& locations, int u, int finish, int fuel){
        //缓存器中有数据则直接取出
        if(cache[u][fuel] != -1){
            return cache[u][fuel];
        }
        int n=locations.size();
        //base case 1:
        //结果0写入缓存器
        if(fuel==0 && u!=finish){
            cache[u][fuel]=0;
            return 0;
        }
        //base case 2:
        bool hasNext = false;
        for(int i=0;i<n;i++){
            //测算当前位置到其他位置需要fuel数
            if(i!=u){
                int need = abs(locations[u]-locations[i]);
                if(fuel>=need){
                    hasNext=true;
                    break;
                }
            }
        }
        if(fuel!=0 && !hasNext ){
            cache[u][fuel]= u==finish?1:0; 
            return cache[u][fuel];
        }

        //真正的主要递归体子项
        int sum=  u==finish?1:0;
        for(int i=0;i<n;i++){
            if(i!=u){
                int need=abs(locations[u]-locations[i]);
                if(fuel>=need){
                   sum+=dfs(locations,i,finish,fuel-need);
                   sum%=mod;
                }
            }
        }
        cache[u][fuel]=sum;
        return sum;
    }
};

简化base case

如果当前位置无法直接到达终点,则无论怎么移动到其他位置也不可能到达终点

将两个base case转化为以下base case:

int need = Math.abs(ls[u] - ls[end]);
        if (need > fuel) {
            cache[u][fuel] = 0;
            return 0;
        }
posted @ 2021-11-30 10:23  秋月桐  阅读(31)  评论(0编辑  收藏  举报