注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
Why in some dp problem, when we define the dp array, sometimes we define the length of array is (length + 1), but sometimes is (length).
Example such as Unique Paths (int[][] dp = new int[m][n];) and Edit distance(int[][] dp = new int[word1.length() + 1][word2.length() + 1];)
Any discussion is appreciated.- public class Solution {
- public int uniquePaths(int m, int n) {
- if(m == 0 || n == 0)
- {
- return 0;
- }
-
- if(m == 1 || n == 1)
- {
- return 1;
- }
-
- int[][] dp = new int[m][n];
-
- for(int i = 0; i < m; i++)
- {
- dp[i][0] = 1;
- }
-
- for(int j = 0; j < n; j++)
- {
- dp[0][j] = 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];
- }
- }
复制代码- public class Solution {
- public int minDistance(String word1, String word2) {
- int len1 = word1.length();
- int len2 = word2.length();
-
- int[][] dp = new int[word1.length() + 1][word2.length() + 1];
-
- for(int i = 0; i <= word1.length(); i++)
- {
- dp[i][0] = i;
- }
-
- for(int j = 0; j <= word2.length(); j++)
- {
- dp[0][j] = j;
- }
-
- for(int i = 0; i < word1.length(); i++)
- {
- for(int j = 0; j < word2.length(); j++)
- {
- char c1 = word1.charAt(i);
- char c2 = word2.charAt(j);
- if(c1 == c2)
- {
- dp[i + 1][j + 1] = dp[i][j];
- }
- else
- {
- dp[i + 1][j + 1] = Math.min(Math.min(dp[i][j + 1] + 1, dp[i + 1][j] + 1), dp[i][j] + 1);
- }
- }
- }
- return dp[len1][len2];
- }
- }
复制代码 |