leetcode@ [72/115] Edit Distance & Distinct subsequences (Dynamic programming)

Source: Internet
Author: User

https://leetcode.com/problems/edit-distance/

Given 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

classSolution { Public:    intMindistance (stringWord1,stringWord2) {        intm = Word1.length (), n =word2.length (); Vector<vector<int> > DP (m+1, vector<int> (n+1,0));  for(intI=0; i<=m;++i) dp[i][0] =i;  for(intj=0; j<=n;++j) dp[0][J] =J;  for(intI=1; i<=m;++i) { for(intj=1; j<=n;++j) {if(word1[i-1] = = word2[j-1]) {Dp[i][j]= Min (dp[i-1][j-1], dp[i-1][j]+1); }                Else{Dp[i][j]= Min (dp[i-1][j], min (dp[i][j-1], dp[i-1][j-1])) +1; }            }        }                returnDp[m][n]; }};
View Code

https://leetcode.com/problems/distinct-subsequences/

Given a string S and a string T, count the number of distinct subsequences of T in S.

A subsequence of a string is a new string which was formed from the original string by deleting some (can be none) of the C Haracters without disturbing the relative positions of the remaining characters. (ie, is a subsequence of and is not "ACE" "ABCDE" "AEC" ).

Here are an example:
S = "rabbbit" , T ="rabbit"

Return 3 .

classSolution { Public:    intNumdistinct (stringSstringt) {intm = s.length (), n =t.length (); Vector<vector<int> > DP (m+1, vector<int> (n+1,0));  for(intI=0; i<=m;++i) dp[i][0] =1;  for(intI=1; i<=m;++i) { for(intj=1; j<=n;++j) {if(s[i-1] = = t[j-1]) Dp[i][j] = dp[i-1][j-1] + dp[i-1][j]; ElseDP[I][J] = dp[i-1][j]; }        }                returnDp[m][n]; }};
View Code

[email protected] [72/115] Edit Distance & Distinct subsequences (Dynamic programming)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.