dp四要素
- 状态(存储小规模问题的结果)
- 方程(状态之间的联系,怎么通过小的状态,来算大的状态)
- 初始化(最极限的小状态是什么)
- 答案(最大的状态是什么)
LeetCode53:最大子序和
(动态规划) O(n)
设
f
(
i
)
f(i)
f(i)表示以第 i个数字为结尾的最大连续子序列的 和 是多少。
初始化
f
(
0
)
=
n
u
m
s
[
0
]
f(0)=nums[0]
f(0)=nums[0]。
转移方程
f
(
i
)
=
m
a
x
(
f
(
i
−
1
)
+
n
u
m
s
[
i
]
,
n
u
m
s
[
i
]
)
)
f(i)=max(f(i−1)+nums[i],nums[i]))
f(i)=max(f(i−1)+nums[i],nums[i]))。可以理解为当前有两种决策,一种是将第 i个数字和前边的数字拼接起来;另一种是第 i 个数字单独作为一个新的子序列的开始。
最终答案为
a
n
s
=
m
a
x
(
f
(
k
)
)
,
0
≤
k
<
n
ans=max(f(k)),0≤k<n
ans=max(f(k)),0≤k<n
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int res;
int n = nums.size();
vector<int> f(n);
f[0] = nums[0]; // init
res = f[0];
for (int i = 1; i < n; i++){
f[i] = max(f[i - 1] + nums[i], nums[i]);
res = max(res, f[i]);
}
return res;
}
};
word break
Given an input string and a dictionary of words, segment the input string into a space=separated dequence of dictionary words if possible. For example, if the input string is "applepie" and dictionary contains a standard set of English words, then we would return the string "apple pie" as output.
bool wordBreak(string s, unordered_set<string> &dict) {
int begin = 0, end = 0;
string word;
bool words[s.size()+1] = {0};
words[0] = true;
for (int i = 1; i < s.size() + 1; i++) {
words[i] = false;
for (end = 0; end < s.size(); end++) {
for(begin = 0; begin <= end; begin++)
if (words[begin] && dict.find( s.substr(begin, end-begin+1) )
!= dict.end()) {
words[end + 1] = true;
break;
}
}
}
return words[s.size()];
}