Tuesday, July 28, 2015

062 - Unique Paths

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.

Hide Tags

Array Dynamic Programming

Hide Similar Problems

(M) Unique Paths II (M) Minimum Path Sum (H) Dungeon Game

 

起先写了个递归的,断然是超时了,

改成动规的,从终点推回到起点,ok了,0ms。

class Solution {
public:
    int uniquePaths(int m, int n)
    {
        int* matrix = new int[m*n];
        memset(matrix, 0, m*n*sizeof(int));
        matrix[(m-1)*n + n-1]=1;
        for(int ii=m-1; ii>=0; ii--)
        {
            for(int jj=n-1; jj>=0; jj--)
            {
                int idx = (ii)*n + jj;
                if(jj<n-1)
                    matrix[idx] += matrix[idx+1];

                if(ii<m-1)
                    matrix[idx] += matrix[idx+n];

            }
        }
        int rst = matrix[0];
        if(matrix)
            delete[] matrix;
        return rst;
    }

 

/********** recursive call, timeout ***********/

    int uniquePaths_timeout(int m, int n) {
        return go(m, n, 0, 0);
    }
   
    int go(int m, int n, int x, int y)
    {
        int rst=0;
       
        if((x==(n-1))&&((0-y)==(m-1)))
            return 1;
       
        if(x<(n-1))
            rst += go(m, n, x+1, y);
       
        if((0-y)<(m-1))
            rst += go(m, n, x, y-1);
        return rst;
    }

};

1 comment:

  1. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    alternatives to kissanime

    ReplyDelete