九章算法5:动态规划II
内容基于九章算法课件
(http://www.jiuzhang.com/)
单序列动态规划
题目:Palindrome Partitioning
Given a string s, cut s into some substrings such that every substring is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Example:
Given s = “aab”,
Return 1 since the palindrome partitioning [“aa”, “b”] could be produced using 1 cut.
这里面需要一个isPalindrome()的函数,这个函数用两个指针做.
题目:Word Break
Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words.
Example:
Given s = “lintcode”, dict = [“lint”, “code”].
Return true because “lintcode” can be break as “lint code”.
hash查长度为L的单词的复杂度为O(L), 所以对于长度为N的string的几乎每个字母,搜索之前的L个位置,每个位置花费时间L,有:
N:字符数
L:每个字符搜索之前的L个字符,即f[j]中j的位置可能在i之前的L个位置之中
L:j+1~i用hash查询是不是一个单词,因最长不超过L,所以长度小于等于O(L)
总时间复杂度:O(N*L*L)即 O(NL2)
双序列动态规划
最长最多问题
题目:LCS
Given two strings, find the longest common subsequence (LCS).
Your code should return the length of LCS.
Example:
For “ABCD” and “EDCA”, the LCS is “A” (or “D”, “C”), return 1.
For “ABCD” and “EACB”, the LCS is “AC”, return 2.
分析:
最小最少问题
题目:Edit distance
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
Example:
Given word1 = “mart” and word2 = “karma”, return 3.
分析:
有几种方案问题
题目:Distinct Subsequence
Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, “ACE” is a subsequence of “ABCDE” while “AEC” is not).
Example:
Given S = “rabbbit”, T = “rabbit”, return 3.
分析:
存在与否问题
题目:Interleaving String
Given three strings: s1, s2, s3, determine whether s3 is formed by the interleaving of s1 and s2.
Example:
For s1 = “aabcc”, s2 = “dbbca”
When s3 = “aadbbcbcac”, return true.
When s3 = “aadbbbaccc”, return false.
分析:
动态规划总结: