A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
How many possible unique paths are there?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { publicintuniquePaths(int m, int n) { if (m == 0 || n == 0) return0; int[][] dp = newint[m + 1][n + 1]; dp[1][1] = 1;
for (inti=1; i <= m; i++) { for (intj=1; j <= n; j++) { if (i == 1 && j == 1) continue; dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } }
return dp[m][n]; } }
优化一下空间复杂度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { publicintuniquePaths(int m, int n) { if (m == 0 || n == 0) return0; int[] dp = newint[n + 1];
for (inti=1; i <= m; i++) { for (intj=1; j <= n; j++) { if (i == 1 && j == 1) dp[1] = 1; else dp[j] += dp[j - 1]; } }
return dp[n]; } }
4 Question-70[★★]
Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
privateintmin(int... args) { intres= Integer.MAX_VALUE; for (inti=0; i < args.length; i++) { res = Math.min(res, args[i]); } return res; } }
6 Question-174[★★★★★]
Dungeon Game
The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0’s) or contain magic orbs that increase the knight’s health (positive integers).
In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.