美文网首页
LeetCode:Longest Common Path

LeetCode:Longest Common Path

作者: Ms柠檬 | 来源:发表于2015-04-02 12:01 被阅读20次

非常经典的题目了: DP经典题目! 比较global maximum和local maximum的问题;

首先你要确定这道题是否可以用动态规划来做,即它是否满足最优化原理和无后效性原则。如果是,就开始设计:
一、确定问题的决策对象
二、对决策对象划分阶段
三、对各阶段确定状态变量
四、根据状态变量确定费用函数和目标函数
五、建立各阶段的状态变量的转移方程,写出状态转移方程
六、编程实现

public int longestCommonSubstring(String A, String B) {
int max = 0;
int[][] d = new int[A.length()+1][B.length()+1];

    for (int i = 0; i < A.length(); i++) {  
        for (int j = 0; j < B.length(); j++) {  
            if (A.charAt(i) == B.charAt(j)) {  
                d[i+1][j+1] = d[i][j] + 1;  
                max = Math.max(max, d[i+1][j+1]);  
            }  
        }  
    }  
    return max;  
}  

相关文章

网友评论

      本文标题:LeetCode:Longest Common Path

      本文链接:https://www.haomeiwen.com/subject/jmsoxttx.html