Leetcode: 576. Out of Boundary Paths
来源:互联网 发布:射频版图设计软件 编辑:程序博客网 时间:2024/04/26 18:46
Leetcode: 576. Out of Boundary Paths
这是一个算所有可能的总数的题目。有一个二维数组,其中一格上面放了一个足球,每次可以往四个方向将球移动一格。已知可以移动N步,求问总共有多少种方法可以将足球移出边界。因为可能有太多种可能了,要求对结果进行一个大数取余mod 109 + 7。
一看就是卡复杂度的题目,用递归这样的栈一定会爆掉的。因为题目是DP的嘛,当然是考虑用DP来求解,通过一定的方法存储中间状态,空间换时间,达到降低时间复杂度的目的。
代码
我们使用一个三维的DP数组,其中dp[k][i][j]表示总共走k步,从(i,j)位置走出边界的总路径数。
其中递归方程应该是:对于dp[k][i][j],走k步出边界的总路径数等于其周围四个位置的走k-1步出边界的总路径数之和。
最后只要返回dp[N][i][j]就是所求结果
class Solution {public: int findPaths(int m, int n, int N, int i, int j) { vector<vector<vector<int>>> dp(N + 1, vector<vector<int>>(m, vector<int>(n, 0))); for (int k = 1; k <= N; ++k) { for (int x = 0; x < m; ++x) { for (int y = 0; y < n; ++y) { long long v1 = (x == 0) ? 1 : dp[k - 1][x - 1][y]; long long v2 = (x == m - 1) ? 1 : dp[k - 1][x + 1][y]; long long v3 = (y == 0) ? 1 : dp[k - 1][x][y - 1]; long long v4 = (y == n - 1) ? 1 : dp[k - 1][x][y + 1]; dp[k][x][y] = (v1 + v2 + v3 + v4) % 1000000007; } } } return dp[N][i][j]; }};
阅读全文
0 0
- 【LeetCode】576. Out of Boundary Paths
- [LeetCode]576. Out of Boundary Paths
- [leetcode]576. Out of Boundary Paths
- Leetcode: 576. Out of Boundary Paths
- [Leetcode] 576. Out of Boundary Paths
- leetcode:Out of Boundary Paths
- 576. Out of Boundary Paths
- 576. Out of Boundary Paths
- [Leetcode] 576. Out of Boundary Paths 解题报告
- Leetcode 576 Out of Boundary Paths
- LeetCode【576】 Out of Boundary Paths
- Out of Boundary Paths
- 576. Out of Boundary Paths(Hard)
- 【leetcode576】Out of Boundary Paths
- Leetcode算法学习日志-576 Out of Boundary Paths
- leetcode 576. Out of Boundary Paths 很棒的DP动态规划做法
- 207. Course Schedule&576. Out of Boundary Paths
- (M)Dynamic Programming:576. Out of Boundary Paths
- ThreadLocal基础详解
- 真分数
- CATIA 二次开发 C#
- spark中application、driver、job、stage的理解
- 一周bug分享
- Leetcode: 576. Out of Boundary Paths
- Android Handler机制
- C++搜索与回溯算法之LETTERS(字母)
- android Apk打包过程概述
- klallalal
- java序列化
- 基于工业以太网(PROFINET)的 SBR工艺污水处理自动控制系统
- python & pycharm 2017.7.3——1
- 1088: [SCOI2005]扫雷Mine 题解