动态规划 DP
Word Break
Given a string s and a dictionary of words dict, determine ifs can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
本题如果暴力,O(2^n),肯定超时,详见https://oj.leetcode.com/discuss/7181/what-time-complexity-recursive-solution-this-problem-how-get
动态规划方法(仅提示)
开一个长度为字符串s长度的bool数组,初始化全部为false,记录从各个字母为起点到结尾的子串是否可以在字典中有分割方案,有就把数组的该位置记为true
从数组的最后一位开始遍历,计算true or false,计算到第一位则结束,最终返回第一位bool值即可
细节请自行思考
--------------------------------------------------------------------------------------------
Word Break II
思路与第一题一样,只是这次需要记录划分结果,并且全部遍历,中途不要continue和break即可
--------------------------------------------------------------------------------------------
Palindrome Partitioning
思路同上
--------------------------------------------------------------------------------------------
Triangle
比较简单的一道动态规划,自底向上计算即可