Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(leetcode46):fix doc
  • Loading branch information
lixiaoyu committed Aug 3, 2020
commit cde7fc0058101d0625e85200aa914f5c1b4c10fd
88 changes: 32 additions & 56 deletions doc/Leetcode46/Leetcode46.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,17 +166,17 @@ $$
}

// 计算所有 DP 值
for (int i = 1; i < m + 1; i++) {
for (int j = 1; j < n + 1; j++) {
int left = dp[i - 1][j] + 1;
int down = dp[i][j - 1] + 1;
int leftDown = dp[i - 1][j - 1];
if (word1[i - 1] != word2[j - 1]){
leftDown += 1;
}
dp[i][j] = min(left, min(down, leftDown));
}
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (word1[i - 1] == word2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
}else {
dp[i][j] = 1 + std::min(dp[i - 1][j],
std::min(dp[i][j - 1],
dp[i - 1][j - 1]));
}
}
}
return dp[m][n];
}
```
Expand Down Expand Up @@ -210,57 +210,33 @@ int editDist(string word1, string word2) {
int m = word1.length();
int n = word2.length();

// Create a DP array to memoize result
// of previous computations
int dp[2][m + 1];
if (m * n == 0) {
return m + n;
}

int dp[2][n + 1];

// To fill the DP array with 0
memset(dp, 0, sizeof dp);

// Base condition when second string
// is empty then we remove all characters
for (int i = 0; i <= m; i++){
for (int i = 0; i <= n; i++){
dp[0][i] = i;
}
// Start filling the DP
// This loop run for every
// character in second string
for (int i = 1; i <= n; i++) {
// This loop compares the char from
// second string with first string
// characters
for (int j = 0; j <= m; j++) {
// if first string is empty then
// we have to perform add character
// operation to get second string
if (j == 0){
dp[i % 2][j] = i;
}
// if character from both string
// is same then we do not perform any
// operation . here i % 2 is for bound
// the row number.
else if (word1[j - 1] == word2[i - 1]) {
dp[i % 2][j] = dp[(i - 1) % 2][j - 1];
}

// if character from both string is
// not same then we take the minimum
// from three specified operation
else {
dp[i % 2][j] = 1 + min(dp[(i - 1) % 2][j],
min(dp[i % 2][j - 1],
dp[(i - 1) % 2][j - 1]));
}
}
}

for (int i = 1; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (j == 0) {
dp[i % 2][j] = i;
}else if (word1[i - 1] == word2[j - 1]) {
dp[i % 2][j] = dp[(i - 1) % 2][j - 1];
}else {
dp[i % 2][j] = 1 + std::min(dp[(i - 1) % 2][j],
std::min(dp[i % 2][j - 1],
dp[(i - 1) % 2][j - 1]));
}
}
}

// after complete fill the DP array
// if the len2 is even then we end
// up in the 0th row else we end up
// in the 1th row so we take len2 % 2
// to get row
return dp[n % 2][m];
return dp[m % 2][n];
}
```

Expand Down