leetcode #72 in cpp
2016-05-31 22:11
357 查看
Solution:
We use DP where dp[i][j] represents minimum steps from word1[0...i-1] to words2[0...j-1]
Code:
class Solution {
public:
int minDistance(string word1, string word2) {
int len1 = word1.length();
int len2 = word2.length();
vector<vector<int>> dp(len1+1, vector<int>(len2+1, 0));//dp[i][j]-->min step convert word1[0..i-1] to word2[0...j-1]
dp[0][0] = 0;
for(int i = 1; i < len2+1; i ++){
dp[0][i] = i;
}
for(int i = 1; i< len1 + 1; i ++){
dp[i][0] = i;
}
for(int i = 1; i < len1+1; i++){
for(int j = 1; j < len2 + 1; j ++){
if(word1[i-1] == word2[j-1]){
dp[i][j] = dp[i-1][j-1];
}else{
//delete word1[i-1] and make word1[0...i-2] to word2[0..j-1], or replace word1[i-1] with word2[j-1]
int mini = min(dp[i-1][j], dp[i-1][j-1]);
//make word1[0...i-1] to word2[0...j-2], insert word2[j-1] into word1
mini = min(mini, dp[i][j-1]);
dp[i][j] = mini + 1;
}
}
}
return dp[len1][len2];
}
};
We use DP where dp[i][j] represents minimum steps from word1[0...i-1] to words2[0...j-1]
Code:
class Solution {
public:
int minDistance(string word1, string word2) {
int len1 = word1.length();
int len2 = word2.length();
vector<vector<int>> dp(len1+1, vector<int>(len2+1, 0));//dp[i][j]-->min step convert word1[0..i-1] to word2[0...j-1]
dp[0][0] = 0;
for(int i = 1; i < len2+1; i ++){
dp[0][i] = i;
}
for(int i = 1; i< len1 + 1; i ++){
dp[i][0] = i;
}
for(int i = 1; i < len1+1; i++){
for(int j = 1; j < len2 + 1; j ++){
if(word1[i-1] == word2[j-1]){
dp[i][j] = dp[i-1][j-1];
}else{
//delete word1[i-1] and make word1[0...i-2] to word2[0..j-1], or replace word1[i-1] with word2[j-1]
int mini = min(dp[i-1][j], dp[i-1][j-1]);
//make word1[0...i-1] to word2[0...j-2], insert word2[j-1] into word1
mini = min(mini, dp[i][j-1]);
dp[i][j] = mini + 1;
}
}
}
return dp[len1][len2];
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解