Tuesday, June 18, 2013

unique path@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?
This problem is quite similar with minimum path sum. We just need to change some beginning condition and change the way they calculate paths.

This is a 2 dimensional dp problem. Since the logic of dp in this problem is simple, we can simplify it as we can only use one array to do it. 

F(m,n) = F(m-1, n) + F(m, n-1), F(0, 0) =0, F(1,0) = 1, F(0,1) 1.

One thing need to pay attention, if we use vector<>, and give value to them by, for example, dp[i][j] = a. We need to declare its size first. Otherwise we can just use push_back. It will cause segmentation fault if we don't give its size. 



No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...