576. Out of Boundary Paths
来源:互联网 发布:淘宝判定为广告的评价 编辑:程序博客网 时间:2024/05/07 03:09
There is an m by n grid with a ball. Given the start coordinate (i,j) of the ball, you can move the ball to adjacent cell or cross the grid boundary in four directions (up, down, left, right). However, you can at most move N times. Find out the number of paths to move the ball out of grid boundary. The answer may be very large, return it after mod 109 + 7.
Example 1:
Input:m = 2, n = 2, N = 2, i = 0, j = 0Output: 6Explanation:
Example 2:
Input:m = 1, n = 3, N = 3, i = 0, j = 1Output: 12Explanation:
Note:
- Once you move the ball out of boundary, you cannot move it back.
- The length and height of the grid is in range [1,50].
- N is in range [0,50].
我的思路:
1、写出递归方法,比较容易想 TLE
class Solution {public: int findPaths(int m, int n, int N, int i, int j) { if(N>=0&&(i==-1||j==-1||i==m||j==n)) return 1; else if(N==0) return 0; int sum=0; sum+=findPaths(m,n,N-1,i-1,j)+findPaths(m,n,N-1,i+1,j)+findPaths(m,n,N-1,i,j-1)+findPaths(m,n,N-1,i,j+1); return sum%(1000000007); }};
2、改成存储版本得动态规划
递归函数的变量有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,-1)));//建立初始化动态规划数组全部是-1.因为0代表没有解决方案 return find(m,n,N,i,j,dp); } int find(int m, int n, int N, int i, int j,vector<vector<vector<int>>>& dp) { if(i==-1||j==-1||i==m||j==n) { return 1; } if(N==0) return 0; if(dp[N][i][j]>=0) return dp[N][i][j];//需要在后面判断,因为可能是越界的 dp[N][i][j]=(((find(m,n,N-1,i-1,j,dp)+find(m,n,N-1,i+1,j,dp))%M+find(m,n,N-1,i,j-1,dp))%M+find(m,n,N-1,i,j+1,dp))%M;//这种取模的情况要把所有的加和后面都取模 return dp[N][i][j]; } int M=1000000007;};
3、递归版本
阅读全文
0 0
- 576. Out of Boundary Paths
- 576. Out of Boundary Paths
- Out of Boundary Paths
- 576. Out of Boundary Paths(Hard)
- 【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
- 【leetcode576】Out of Boundary Paths
- leetcode:Out of Boundary Paths
- 207. Course Schedule&576. Out of Boundary Paths
- (M)Dynamic Programming: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 很棒的DP动态规划做法
- 第十二周:( LeetCode576) Out of Boundary Paths(c++)
- 513. Find Bottom Left Tree Value 树 BFS
- 19. Remove Nth Node From End of List
- 浅析JVM类加载机制
- 515. Find Largest Value in Each Tree Row 找到数每一层的最大值
- C++动态分配内存空间 : new 和 delete
- 576. Out of Boundary Paths
- 638. Shopping Offers 深度优先遍历、递归、存储技术(基于递归的动态规划)
- oracle触发器分类
- redis的自启设置
- DFS(深度搜索)——基于回溯法和递归
- Unity学习2 鼠标点击控制物体移动
- C++语法基础之关键字与标识符(10月4日暂存)
- 295. Find Median from Data Stream 剑指offer 数据流中的中位数
- 42. Trapping Rain Water 及类似题目 407. Trapping Rain Water II 11. Container With Most Water