在前面我们谈到了一些简单的用动态规划解决的问题:
动态规划(一):从Fibonacci数列谈起
但是,在DP问题里,我们很多时候对于状态方程的递推,往往更加复杂,我们看以下几道题:
A.字符串分割
题目难度:Medium
题目来源:牛客网
题目描述:
Given a string s and a dictionary of words dict, determine if s 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".
1.定义状态:F(i)---第i个字符是否可以被字典中的词分割
2.状态方程:j<i && dict.find(s.substr(j,i-j)&&F(j)
3.初始值:F(0) = true
4.返回值: F(n)
代码如下:
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
if(s.empty())
return false;
if(dict.empty())
return false;
vector<bool>wb(s.size() + 1,false);
wb[0] = true;
for(int i = 1; i <= s.size();i++)
{
fo