LeetCode 63. 不同路径 II

LeetCode 63. 不同路径 II
在这里插入图片描述
暴力会超时

记忆化搜索

const int N = 110;
class Solution {
public:
    int f[N][N];
    int n, m;
    int dfs(int x, int y, vector<vector<int>>& g)
    {
        if(f[x][y]) return f[x][y];
        if(g[x][y] == 1)
        {
            f[x][y] = 0;
            return f[x][y];
        }
        if(n - 1 == x && y == m - 1)
        {
            f[x][y] = 1;
            return f[x][y];
        }
        int res1 = 0, res2 = 0;
        if(x + 1 < n && g[x + 1][y] == 0)
            f[x + 1][y] = dfs(x + 1, y, g);
        if(y + 1 < m && g[x][y + 1] == 0)
            f[x][y + 1] = dfs(x, y + 1, g);
        return f[x][y + 1]+ f[x + 1][y];
    }
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        n = obstacleGrid.size(), m = obstacleGrid[0].size();
        return dfs(0, 0,obstacleGrid);

    }
};

经典DP

const int N = 110;
class Solution {
public:
    int f[N][N];
    int uniquePathsWithObstacles(vector<vector<int>>& g) {
        int n = g.size(), m = g[0].size();

        f[0][0] = 1;
        for(int i = 0; i < n; i ++)
            for(int j = 0; j < m; j ++)
            {
                if(g[i][j] == 1)
                    f[i][j] = 0;
                if(g[i][j] == 0 && j - 1 >= 0)
                    f[i][j] += f[i][j - 1];
                if(g[i][j] == 0 && i - 1 >= 0)
                    f[i][j] += f[i - 1][j];
                
            }
        return f[n - 1][m - 1];
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值