LeetCode 62. Unique Paths

来源:互联网 发布:java测试需要会什么 编辑:程序博客网 时间:2024/06/16 20:07

问题描述:

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?

算法思路:

如果机器人要走到 [ i , j ] 位置,他只有两种方法(1)从[ i , j-1 ] 往下走(2)从[ i-1 , j ] 往右走,这样就变成了一个递归问题。使用数组来解,每个位置记录着机器人从start point到达该点的方法


算法:

class Solution {public:    int uniquePaths(int m, int n) {        int arr[100][100];arr[0][0] = 1;for(int i=0;i<m;i++)for (int j = 0; j < n; j++) {    if (i==0&&j==0)        continue;if (i == 0)arr[i][j] = arr[i][j - 1];else if (j == 0)arr[i][j] = arr[i - 1][j];elsearr[i][j] = arr[i - 1][j] + arr[i][j - 1];}return arr[m-1][n-1];    }};