62-Unique Paths

来源:互联网 发布:sql 奖学金加200 编辑:程序博客网 时间:2024/06/11 11:41

类别:dynamic programming
难度:medium

题目描述

https://leetcode.com/problems/unique-paths/description/
这里写图片描述

算法分析

单纯的只往下走或者是单纯的只往右走,都只有一种可能的走法,所以初始化的时候path[i][0] = path[0][j] = 1
对于每一个位置,走到这里的上一步可能是从上面下来或者是从左边过来,所以path[i][j] = path[i - 1][j] + path[i][j - 1]

代码实现

//  for every position, can be from left or up, and so there is //  path[i][j] = path[i - 1][j] + path[i][j - 1];class Solution {public:    int uniquePaths(int m, int n) {        //  二维数组        vector<vector<int> > path(m, vector<int>(n,1));        for (int i = 1; i < m; ++i) {            for (int j = 1; j < n; ++j) {                path[i][j] = path[i - 1][j] + path[i][j - 1];            }        }        return path[m-1][n-1];    }};
原创粉丝点击