leetcode@ [72/115] Edit Distance & Distinct Subsequences (Dynamic Programming)
2015-12-06 18:19
525 查看
https://leetcode.com/problems/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:
a) Insert a character
b) Delete a character
c) Replace a character
用dp[i][j] 来表示 长度为 i 的 word1 经过 dp[i][j]次变换 可以得到长度为 j 的word2,那么我们主要考察两种情况,第一种是:word1[i] == word2[j],那么这个问题的规模便转换成了:dp[i][j] = dp[i-1][j-1]. 第二种情况是:word1[i] != word2[j],那么我们可以删除掉word1中的第 i 个字符,或者我们可以把 word1中的第 i 个字符换成与 word2[j] 相同的字符,或者我们还可以同时 删除 word1[i] 和 word2[j]. 于是状态转移方程为:dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1.
View Code
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:
a) Insert a character
b) Delete a character
c) Replace a character
用dp[i][j] 来表示 长度为 i 的 word1 经过 dp[i][j]次变换 可以得到长度为 j 的word2,那么我们主要考察两种情况,第一种是:word1[i] == word2[j],那么这个问题的规模便转换成了:dp[i][j] = dp[i-1][j-1]. 第二种情况是:word1[i] != word2[j],那么我们可以删除掉word1中的第 i 个字符,或者我们可以把 word1中的第 i 个字符换成与 word2[j] 相同的字符,或者我们还可以同时 删除 word1[i] 和 word2[j]. 于是状态转移方程为:dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1.
class Solution { public: int numDistinct(string s, string t) { int m = s.length(), n = t.length(); vector<vector<int> > dp(m+1, vector<int>(n+1, 0)); for(int i=0;i<=m;++i) dp[i][0] = 1; for(int i=1;i<=m;++i) { for(int j=1;j<=n;++j) { if(s[i-1] == t[j-1]) dp[i][j] = dp[i-1][j-1] + dp[i-1][j]; else dp[i][j] = dp[i-1][j]; } } return dp[m] ; } };
View Code
相关文章推荐
- hdu 1242Rescue(DFS)
- iOS获取设备UUID
- UGUI中image不能使用旧版Animation
- 【iOS】UITbableView中cell的单选状态和多选状态
- vuejs学习资料
- 数据注解属性--Required
- zoj 3792 Romantic Value
- UICollectionView简单介绍
- iOS系列UI篇——自定义UIButton
- iOS动画和特效(一)UIView动画和CoreAnimation
- std::deque
- iOS之UI--通讯录的实例关键知识技术点积累
- java 向 mysql 插入汉字 Incorrect string value 解决办法
- CALayer --> UIView
- UI开发推荐颜色
- UICollectionView(集合视图)以及自定义集合视图
- UITabbarViewController代码重构
- android.util.AndroidRuntimeException: requestFeature() must be called before adding content
- ignoreAnchorPointForPosition(true) == 锚点(0,0)
- “简单证明GUID(全局唯一标识符)并不唯一”