LeetCode 62. Unique Paths
题目如下:
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? Note: m and n will be at most 100.
思路:
首先,当n=1,或m=1时,结果res[1][n] = res[m][1] = 1,这是边界情况;
否则,每次只有往下或往右走一步两种情况, 故res[m][n] = res[m-1][n] + res[m][n-1];
算法效率O(m*n)
本体代码:
import java.util.Scanner; /** * Created by yuanxu on 17/4/13. */ public class DP62 { public static int uniquePaths(int m, int n) { int res[][] = new int[m+1][n+1];
// 边界情况 if (m<1 || n<1) { return 0; } for (int i=1; i<=m; i++) { res[i][1] = 1; } for (int j=1; j<=n; j++) { res[1][j] = 1; } // dp for (int i=2; i<=m; i++) { for (int j=2; j<=n; j++) { res[i][j] += res[i-1][j] + res[i][j-1]; // System.out.println("i="+i+"j="+j+"res="+res[i][j]); } } return res[m][n]; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int m = scanner.nextInt(); int n = scanner.nextInt(); System.out.println(uniquePaths(m, n)); } }