Sunday, June 28, 2015

Unique Paths I, II

A robot is located at the top-left corner of am 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?
Have you met this question in a real interview? 
Yes
Example
1,11,21,31,41,51,61,7
2,1





3,1




3,7

Above is a 3 x 7 grid. How many possible unique paths are there?

Note
m and n will be at most 100.
public class Solution {
    /**
     * @param n, m: positive integer (1 <= n ,m <= 100)
     * @return an integer
     */
    public int uniquePaths(int m, int n) {
        // write your code here 
        int[] num = new int[n];
       Arrays.fill(num, 1);
       
       for(int i = 1; i < m; i++){
           for(int j = 1; j < n; j++){
                num[j] = num[j-1] + num[j]; 
           }
       }
       return num[n-1];
    }
}

Unique Paths II


Easy Unique Paths II

27%
Accepted
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 as1 and 0 respectively in the grid.
Have you met this question in a real interview? 
Yes
Example
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.

public class Solution {
    /**
     * @param obstacleGrid: A list of lists of integers
     * @return: An integer
     */
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        // write your code here
        int m = obstacleGrid.length, n = obstacleGrid[0].length;
        int[] num = new int[n];
        num[0] = obstacleGrid[0][0] == 0 ? 1 : 0;
        for(int i = 1 ; i < n; i++){
            num[i] = num[i-1] == 0 ? 0 : obstacleGrid[0][i] == 0 ? 1 : 0;  
        }
       
       for(int i = 1; i < m; i++){
           num[0] = num[0] == 0 ? 0 : obstacleGrid[i][0] == 0 ? 1 : 0;
           for(int j = 1; j < n; j++){
                 num[j] = obstacleGrid[i][j] == 1 ? 0 : num[j] + num[j-1];
           }
       }
       return num[n-1];
    }
}

No comments:

Post a Comment