leetcode #72 in cpp

原创 2016年05月31日 22:11:40


We use DP where dp[i][j] represents minimum steps from word1[0...i-1] to words2[0...j-1]


class Solution {
    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];
                    //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 #36 in cpp.

The question is to determine a Sudoku is valid.  Solution:  if a Sudoku is valid, each row, each co...

*leetcode 138 in cpp

A linked list is given such that each node contains an additional random pointer which could point t...

leetcode #17 in cpp

The question is : Given a digit string, return all possible letter combinations that the number coul...

leetcode $42 in cpp

Code: (This method is not the best one. There are other methods using two pointers) Key: a bar coul...

*leetcode #80 in cpp

Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For example, G...

Leetcode 116. Populating Next Right Pointers in Each Node (Medium) (cpp)

Leetcode 116. Populating Next Right Pointers in Each Node (Medium) (cpp)
  • Niko_Ke
  • Niko_Ke
  • 2016年12月27日 02:35
  • 224

Leetcode 25. Reverse Nodes in k-Group (Hard) (cpp)

Leetcode 25. Reverse Nodes in k-Group (Hard) (cpp)
  • Niko_Ke
  • Niko_Ke
  • 2016年12月10日 04:04
  • 169

Leetcode 230. Kth Smallest Element in a BST (Medium) (cpp)

Leetcode 230. Kth Smallest Element in a BST (Medium) (cpp)
  • Niko_Ke
  • Niko_Ke
  • 2016年08月23日 11:17
  • 293

leetcode #60 in cpp

The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of ...

Leetcode #91 in cpp

A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A...
您举报文章:leetcode #72 in cpp