九章算法5:动态规划II

九章算法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.

分析:
这里写图片描述

动态规划总结:

这里写图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值