码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Unique Paths I & II

时间:2015-04-30 12:23:37      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

Title:

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.

 

思路:直观的思路是使用递归,但是会超时

class Solution{
public:
    int m;
    int n;
    int uniquePaths(int m, int n) {
        this->m = m;
        this->n = n;
        int sum = 0;
        fun(1,1,sum);
        return sum;
    }
    void fun(int i,int j,int& sum){
        if (i == m && j == n)
            sum++;
        if (i > m || j > n)
            return ;
        fun(i+1,j,sum);
        fun(i,j+1,sum);
    }
};

一般这种递归都可以使用动态规划来解决

class Solution{
public:
    int uniquePaths(int m,int n){
        if (m < 1 || n < 1)
            return 0;
        vector<int> v(n,1);
        for (int i = 1; i < m ; i++)
            for (int j = 1; j < n;j++){
                v[j] += v[j-1];
            }
        return v[n-1];
    }
};

Unique Path II

Follow up for "Unique Paths":

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

For example,

There is one obstacle in the middle of a 3x3 grid as illustrated below.

[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]

The total number of unique paths is 2.

Note: m and n will be at most 100.

开始想直接使用I中的,却没有考虑到边界上有障碍的情况

int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid){
            if (obstacleGrid.empty())
                return 0;
            int m = obstacleGrid.size();
            int n = obstacleGrid[0].size();
            if (m < 1 || n < 1)
                return 0;
            vector<int> result(n);
            result[0] = 1;
            for (int i = 0 ; i < m ; i++){
                for (int j = 0 ; j < n ; j++){
                    if (obstacleGrid[i][j] == 1)
                        result[j] = 0;
                    else{
                        if (j > 0)
                            result[j] += result[j-1];
                    }
                }
            }
            return result[n-1];
        }

 

LeetCode: Unique Paths I & II

标签:

原文地址:http://www.cnblogs.com/yxzfscg/p/4468344.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!