[LeetCode]62. Unique Paths

来源:互联网 发布:服装设计软件cad 编辑:程序博客网 时间:2024/06/05 11:26

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?

这里写图片描述

代码

class Solution {public:    int a[101][101] = {0};    int uniquePaths(int m, int n) {        a[1][1] =1;        for(int i = 1; i<=m;++i)            for(int j = 1; j<=n;++j)                if(!(i == 1 && j == 1))                    a[i][j] = a[i-1][j]+a[i][j-1];        return a[m][n];    }};

代码分析

以3*3的矩阵为例
这里写图片描述
图中为到各个位置有多少种方法。
可以分析+观察可以得出
到(i,j)的方法个数为所有前一步所走的方法之和
例如f(3,2) = f(3,1)+f(2,2) = 1+2=3
则得到递推公式 f(i,j) = f(i-1,j)+f(i,j-1)

原创粉丝点击