classSolution {publicintuniquePaths(int m,int n) {int dp[][] =newint[m][n];for (int i =0; i < m; i++) dp[i][0] =1; // from left top cornerfor (int i =0; i < n; i++) dp[0][i] =1;for (int i =1; i < m; i++) {for (int j =1; j < n; j++) { dp[i][j] = dp[i-1][j] + dp[i][j-1]; } }return dp[m-1][n-1]; }}
from bottom...ๅคชไธ็ด่ฆบไบ
classSolution {publicintuniquePaths(int m,int n) {int dp[][] =newint[m][n];for (int i =0; i < m; i++) dp[i][n-1] =1; // from buttonfor (int i =0; i < n; i++) dp[m-1][i] =1;for (int i = m-1; i >0; i--) {for (int j = n-1; j >0; j--) { dp[i-1][j-1] = dp[i-1][j] + dp[i][j-1]; } }return dp[0][0]; }}
a little optimization of the space, 1-D array
ๅ ถๅฏฆๅฏไปฅไธ่กไธ่ก็ดฏๅ ไธไพ
ๅ ็บๅช่ฆ่จ็ฎ็ด ๅก็้จๅ, ๆไปฅ ้ๆฎต for loop ้ฝๅพ 1 ้ๅง
for (int i =1; i < m; i++) { // row, from 1 startfor (int j =1; j < n; j++) { // column dp[j] += dp[j-1]; } }
ๅ ็บๅๅงไบindex 0, row ๅ col
้ฝ็บ 11111, ๆ่ฉฒ่ชชๅช้่ฆๅๅง row index = 0็ 11111