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 #32 in cpp

Given a string containing just the characters '(' and ')', find the length of the longest valid (we...

leetcode #114 in cpp

Given a binary tree, flatten it to a linked list in-place. For example, Given 1 ...

leetcode #160 in cpp

Write a program to find the node at which the intersection of two singly linked lists begins. F...

Leetcode 285. Inorder Successor in BST (Medium) (cpp)

Leetcode 285. Inorder Successor in BST (Medium) (cpp)

leetcode #98 in cpp

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined...

leetcode #37 in cpp

The question is to solve a Sudoku. Solution: We scan through the Sudoku. Whenever we meet a '.', w...

leetcode #77 in cpp

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For exa...

leetcode #139 in cpp

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa...

leetcode #18 in cpp

The question is similar to 3sum. And how to solve it is thus very similar to the solution of 3sum.  ...

leetcode #44 in cpp

Solution:  We use DP to solve this problem.  Initialize bool dp[pattern length + 1][ s length + 1]...