Rolling Array

2-D array, rolling in an array

  1. The array has 2 states, cur and pre

  2. If dp[i] needs the updates from cur and pre, rolling from head; if dp[i] needs the both updates from pre, rolling form tail

62 Unique Path

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).How many possible unique paths are there?

// Tran: dp[i][j] = dp[i-1][j] + dp[i][j-1]
// Init: dp[i][0] = dp[0][j] = 0
// Ans: dp[m-1][n-1]
public int uniquePaths(int m, int n) {
    int[][] dp = new int[n][m];
    for(int i=0; i<n; i++) dp[i][0] = 1;
    for(int j=0; j<m; j++) dp[0][j] = 1;

    for(int i=1; i<n; i++){
        for(int j=1; j<m; j++){
            dp[i][j] = dp[i-1][j] + dp[i][j-1];
        }
    }
    return dp[n-1][m-1];
}
  • Improve 1: dp[i][j] only relates to dp[i-1][j], dp[i][j-1]. We only needs to maintain 2 rows and switch the row every row iteration. Space O(2n)

  • Improve 2: dp[i][j] can be update by just dp[i-1][j] and current dp[i][j]. Space O(n)

64 Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

  1. Init first column and first column

  2. f[i][j] = min{f[i-1][j], f[i][j-1]} + A[i][j]

  • Rolling array

72. Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

Insert a character Delete a character Replace a character

  • State: f[i][j]表示s1前i個字符經過幾次編輯可以變成s2前j個字符

  • Func: f[i][j] = f[i-1][j-1], s1[i-1]=s2[j-1] 不用編輯

    f[i][j] = 1+ min{f[i-1][j-1],f[i-1][j],f[i][j-1]}

  • Rolling Array

  • Use pre to record dp[i-1][j-1]

221. Maximal Square

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

  • State: dp[i][j]是包含matrix[i-1][j-1]的最小邊長

  • Func: if(matrix[i-1][j-1]==1) dp[i][j]=min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1

  • Ans: dp[m+1][n+1]

1 Time O(mn), Space O(mn)

2 Time O(m*n), Space O(n)

  • A value pre the record the dp[i-1][j-1] value

  • Update dp[j] if not '1'

=> Compare Maximal Rectangle

304. Range Sum Query 2D - Immutable

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8

Last updated

Was this helpful?