classSolution{ // 记忆化加递归 int[][] memo; publicintuniquePaths(int m, int n){ memo = newint[m][n]; return dfs(m - 1, n - 1); }
privateintdfs(int m, int n){ // 1.边界 if (m <= 0 || n <= 0) { return1; } // 2. 剪枝 if (memo[m][n] != 0) return memo[m][n]; // 3. 递归 int res = dfs(m - 1, n) + dfs(m, n - 1); return memo[m][n] = res; } }
然后dp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution{ publicintuniquePaths(int m, int n){ int[][] dp = newint[m][n]; for (int i = 0; i < m; i++) dp[i][0] = 1; for (int j = 0; j < n; j++) dp[0][j] = 1;
for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } return dp[m - 1][n - 1]; } }