Unique Paths [LeetCode]

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.

Solution: Pretty easy, use dynamic programming, from bottom line to top line, caculate every the path num of every cell.

 1 class Solution {
 2 public:
 3     int uniquePaths(int m, int n) {
 4         if(m <= 0 || n <= 0)
 5             return 0;
 6         vector<int> nums;
 7         for(int i = 0; i < m; i ++) {
 8             if(i == 0) {
 9                 for(int j = 0; j < n; j++)
10                     nums.push_back(1);
11             } else {
12                 for(int j = 1; j < n; j ++) {
13                     nums[j] += nums[j - 1];
14                 }
15             }
16         }
17         return nums[n - 1];
18     }
19 };

 

posted @ 2013-11-02 12:16  假日笛声  阅读(197)  评论(0编辑  收藏  举报