LeetCode 62 — Unique Paths(C++ Java Python)
来源:互联网 发布:彭雪茹 知乎 编辑:程序博客网 时间:2024/06/05 09:37
题目:http://oj.leetcode.com/problems/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?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
题目翻译:
机器人位于m x n网格的左上角(标有'Start')。
在任何时间,机器人只能向下或向右移动。机器人试图到达网格的右下角(标有'Finish')。
有多少种可能的不同路径?
注意:m和n最大为100。
分析:
使用二维数组来实现。规律为除了第一行和第一列全为1外,其他格的路径数为其上一格和左一格的和。
C++实现:
<span style="font-size:14px;"> int A[m][n]; for(int i = 0; i < m; ++i) { A[i][0] = 1; } for(int i = 1; i < n; ++i) { A[0][i] = 1; } for(int i = 1; i < m; ++i) for(int j = 1; j < n; ++j) { A[i][j] = A[i][j - 1] + A[i - 1][j]; } return A[m - 1][n - 1];</span>Java实现:
<span style="font-size:14px;">public class Solution { public int uniquePaths(int m, int n) { int[][] A = new int[m][n];for (int i = 0; i < m; ++i) {A[i][0] = 1;}for (int i = 1; i < n; ++i) {A[0][i] = 1;}for (int i = 1; i < m; ++i)for (int j = 1; j < n; ++j) {A[i][j] = A[i][j - 1] + A[i - 1][j];}return A[m - 1][n - 1]; }}</span>Python实现:
<span style="font-size:14px;">class Solution: # @return an integer def uniquePaths(self, m, n): paths = [[1] for i in range(m)] # initialize the 1st column to be 1 for i in range(n - 1): # initialize the 1st row to be 1 paths[0].append(1) for i in range(m - 1): for j in range(n - 1): paths[i + 1].append(paths[i][j + 1] + paths[i + 1][j]) return paths[m - 1][n - 1]</span>
感谢阅读,欢迎评论!
0 0
- LeetCode 62 — Unique Paths(C++ Java Python)
- LeetCode 63 — Unique Paths II(C++ Java Python)
- leetcode 62 C++. Unique Paths
- [leetcode]Unique Paths(C)
- 【Leetcode】【python】Unique Paths/Unique Paths II
- LeetCode(62)Unique Paths
- Leetcode(62)Unique Paths
- [Leetcode] Unique Paths (Java)
- [LeetCode][Java] Unique Paths
- LeetCode 62. Unique Paths (Python)
- LeetCode 63. Unique Paths II (Python)
- [leetcode 62] Unique Paths
- LeetCode(62): Unique Paths
- [LeetCode 62]Unique Paths
- leetcode || 62、Unique Paths
- Unique Paths - LeetCode 62
- leetcode-62 Unique Paths
- Leetcode[62]-Unique Paths
- Visual C#自身没有类库
- 定时器线程
- Android电池信息的获取
- AndroidManifest.xml中application name功能介绍 .
- Matlab与VC混合
- LeetCode 62 — Unique Paths(C++ Java Python)
- android textview或者edittext显示像QQ那样的图片
- 继承extends
- SQL查询基本结构
- 物理全明星梦之队
- 阅读优秀代码是提高开发人员修为的一种捷径
- js(复选框,全选,全部选,反选教程)
- 一个关于使用String做锁的问题(PS:不要使用string做锁)
- JVM中方法区