Longest Common Subsequence

复盘

go多层map嵌套 , 每层map都要初始化

既要写极端小的也要写极端大的用例

自底向上 , 状态 ,状态转移函数还没写 , 要搞懂啊

画图

最长公共子序列 Longest Common Subsequence

未添加记忆化搜索的伪代码

findLCSLenin( lstr,rstr ,p1 , p2 )
    if p1==-1 or p2==-1
        return 0

    maxLen=0
    if lstr[p1]==rstr[p2]
        maxLen++
        maxLen+=findLCSin(lstr,rstr,p1-1,p2-1)

    else {
        max=max(findLCSin(lstr,rstr,p1-1,p2) , 
                findLCSin(lstr,rstr,p1,p2-1)))
        maxLen+=max
    }

    return maxLen

添加了记忆化搜索的go 实现

type Solution struct {
    memo map[int]map[int]int
}

func (t *Solution)findLCSLenIn(lstr string,rstr string,p1 int,p2 int) int{
    if p1==-1 || p2==-1 {
        return 0
    }

    if _,ok:=t.memo[p1];!ok{
        t.memo[p1]=make(map[int]int)
    }
    if  _,ok:=t.memo[p1][p2];ok{
        //fmt.Println("memo work")
        return t.memo[p1][p2]
    }

    maxLen:=0
    if lstr[p1]==rstr[p2] {
        maxLen++
        maxLen+=t.findLCSLenIn(lstr,rstr,p1-1,p2-1)
    } else {
        maxLen+=maxC(t.findLCSLenIn(lstr,rstr,p1-1,p2),t.findLCSLenIn(lstr,rstr,p1,p2-1))
    }
    t.memo[p1][p2]=maxLen
    return maxLen
}

func maxC(v1 int ,v2 int) int{
    if v1>v2 {
        return v1
    }
    return v2
}

测试用例

func main() {
    testCase:=[][]string{
        {"ABCD","AEBD"},
        {"",""},
        {"A",""},
        {"","AD"},
        {"afsfwabgdfedfs","fsdfwefwgfsdfsabgdfef"},
    }

    for _,v:=range testCase {
        solution:=Solution{make(map[int]map[int]int)}
        res:=solution.findLCSLenIn(v[0],v[1],len(v[0])-1,len(v[1])-1)
        fmt.Println(res)
        fmt.Println(solution.memo)
    }

}

输出

3
map[3:map[3:3] 2:map[0:1 1:1 2:2] 1:map[2:2 0:1 1:1] 0:map[0:1 1:1]]
0
map[]
0
map[]
0
map[]
11
map[13:map[20:11 13:9 14:9 15:9 16:9 17:9 18:9 19:10] 3:map[3:3 4:3 10:3 11:3 6:3 8:3 5:3 2:2 12:3 13:3 0:1 1:2 9:3 7:3] 0:map[1:0 6:0 8:0 9:0 10:0 11:0 0:0 2:0 3:0 4:0 5:0 7:0] 7:map[10:5 16:7 6:4 11:5 3:3 7:4 1:2 8:5 9:5 12:5 13:5 14:5 15:6 0:1 2:2 4:4 5:4] 5:map[14:5 8:4 10:4 11:4 1:2 2:2 3:3 4:4 5:4 6:4 7:4 13:4 0:1 9:4 12:4] 4:map[7:4 0:1 1:2 2:2 13:4 4:4 5:4 3:3 9:4 12:4 6:4 8:4 10:4 11:4] 1:map[3:1 0:1 2:1 12:1 10:1 11:1 8:1 5:1 1:1 9:1 6:1 7:1 4:1] 12:map[14:8 15:8 17:8 12:8 18:9 19:10 13:8 16:8 20:11] 10:map[10:6 12:7 18:9 6:5 9:6 15:7 19:10 14:7 7:5 8:5 11:6 13:7 16:7 17:8 5:5] 9:map[10:6 17:8 4:4 18:9 12:7 13:7 15:7 8:5 3:4 14:7 16:7 9:6 11:6 6:5 7:5] 8:map[17:8 3:3 7:4 9:5 10:5 15:6 2:3 8:5 5:4 11:6 16:7 4:4 6:4 12:6 13:6 14:6] 2:map[10:2 3:2 4:2 6:2 7:2 8:2 13:2 11:2 1:2 2:2 5:2] 11:map[19:10 11:7 12:7 14:7 15:7 17:8 18:9 13:7 16:7] 6:map[15:6 10:4 11:4 12:4 13:4 1:2 3:3 4:4 6:4 14:5 0:1 2:2 7:4 9:4 5:4 8:4]]

待完善 : 自底向上的动态规划写法 , 并写出状态和状态转移函数

你可能感兴趣的:(Longest Common Subsequence)