leetcode 72. Edit Distance 編輯距離-動態規劃、滾動數組

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

1.動態規劃,二維數組

class Solution {
public:
    int minDistance(string word1, string word2) {
        if(word1.empty() || word1.length()==0)
            return word2.length();
        if(word2.empty() || word2.length()==0)
            return word1.length();

        int row = word1.length();
        int col = word2.length();

        int a[row+1][col+1];
        int i, j, k;
        for(i=0;i<col+1;i++)//第一行
            a[0][i]=i;
        for(i=0;i<row+1;i++)//第一列
            a[i][0]=i;
        
        for(i=1;i<row+1;i++){
            for(j=1;j<col+1;j++){
                if(word1[i-1]==word2[j-1]){//這裏需要注意字符的下標需要減1
                    a[i][j]=a[i-1][j-1];
                }
                else{
                    int tmp = min(a[i][j-1], a[i-1][j]);//插入、刪除
                    tmp = min(tmp, a[i-1][j-1]);//修改
                    a[i][j]=1+tmp;//取3種方法的最小值,再加上1
                }
            }
        }
        return a[row][col];
    }
};

2.動態規劃,一維滾動數組

在更新a[i][j]時,只會用到左上角a[i-1][j-1]、左側a[i][j-1]、上側a[i-1][j] 這三個值,用二維數組明顯浪費內存。

只要將a[i][j]左側的所有值,以及上一行所有值保存到一個一位數組,不斷滾動更新即可。

class Solution {
public:
    int minDistance(string word1, string word2) {
        if(word1.empty() || word1.length()==0)
            return word2.length();
        if(word2.empty() || word2.length()==0)
            return word1.length();
        int row = word1.length();
        int col = word2.length();
        
        int a[col+1];
        
        int i, j;
        for(i=0;i<col+1;i++)
            a[i]=i;
        
        for(i=1;i<row+1;i++){
            int left_up = a[0]; //記錄原來二維數組中左上角 改 的值
            a[0]=i;//更新原來二維數組中左側 插入 的值
            
            for(j=1;j<col+1;j++){
                int x = a[j];//記錄原來二維數組上側 刪 的值
                if(word1[i-1]==word2[j-1]){
                    a[j]=left_up;
                }
                else{
                    int tmp = min(a[j-1], a[j]);
                    tmp = min(tmp, left_up);
                    a[j]=1+tmp;
                }
                left_up = x;//當前 刪 的值,到下一個字符時已經變爲左上角的 改 了
            }
        }
        return a[col];
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章