DP EASY 21.11.09
动态规划三要素
- 边界
- 最优子结构
- 状态转移函数
53. 最大子序和
- 边界 f(1)=nums[0]
- 最优子结构 f(i-1) 和nums[i]
- 状态转移函数:
-2 | 1 | -3 | 4 | -1 | 2 | 1 | -5 | 4 | |
---|---|---|---|---|---|---|---|---|---|
Pre | -2 | 1 | -2 | 4 | 3 | 5 | 6 | 1 | 5 |
Max | -2 | 1 | 1 | 4 | 4 | 5 | 6 | 6 | 6 |
Java实现
- 两条数组,空间复杂度高
class Solution {
public int maxSubArray(int[] nums) {
int len = nums.length;
int[] subMax = new int[len];
int[] ans = new int[len];
subMax[0] = nums[0];
ans[0] = nums[0];
for (int i = 1; i < len; i++){
if (subMax[i - 1] + nums[i] > nums[i]){
subMax[i] = subMax[i - 1] + nums[i];
}else {
subMax[i] = nums[i];
}
if (subMax[i] > ans[i - 1]){
ans[i] = subMax[i];
}else {
ans[i] = ans[i - 1];
}
}
return ans[len - 1];
}
}
执行用时:3 ms, 在所有 Java 提交中击败了12.48%的用户
内存消耗:54.4 MB, 在所有 Java 提交中击败了5.02%的用户
- 两个变量
class Solution {
public int maxSubArray(int[] nums) {
int pre = nums[0], ans = nums[0];
for (int i = 1; i < nums.length; i++){
pre = Math.max(pre + nums[i], nums[i]);
ans = Math.max(ans, pre);
}
return ans;
}
}
执行用时:1 ms, 在所有 Java 提交中击败了94.15%的用户
内存消耗:48.5 MB, 在所有 Java 提交中击败了25.27%的用户
新增知识:
//求最大值
x = Math.max(a, b);
// x= Math.min(a, b);
//同类型变量声明及赋值可以用逗号隔开
int x = 3, y = 5;
392. 判断子序列
Java实现
1、双指针
class Solution {
public boolean isSubsequence(String s, String t) {
int j = 0, slen = s.length(), tlen = t.length(), k = 0;
for (int i = 0; i < slen; i++){
while (j < tlen){
if (s.charAt(i) != t.charAt(j)){
j++;
}else {
j++;
k++;
break;
}
}
}
if (k != slen){
return false;
}else {
return true;
}
}
}
改进:
class Solution {
public boolean isSubsequence(String s, String t) {
int j = 0, slen = s.length(), tlen = t.length(), k = 0;
while (j < slen && k < tlen){
if (s.charAt(j) == t.charAt(k)){
j++;
}
k++;
}
return j == slen;
}
}
2、动态规划
???脑阔疼
746. 使用最小花费爬楼梯
- 边界:在0,1台阶时花费为0
- 最优子结构
- 状态转移方程:当前花费 等于 前两个台阶的花费 加上 本身的花费 的最小值
台阶 | 1 | 100 | 1 | 1 | 1 | 100 | 1 | 1 | 100 | 1 | |
---|---|---|---|---|---|---|---|---|---|---|---|
costSum | 0 | 0 | 1 | 2 | 2 | 3 | 3 | 4 | 4 | 5 | 6 |
台阶 | 10 | 15 | 20 | 2 | |
---|---|---|---|---|---|
costSum | 0 | 0 | 10 | 15 | 17 |
Java实现
- 数组
class Solution {
public int minCostClimbingStairs(int[] cost) {
int len = cost.length;
int[] ans = new int[len + 1];
ans[0] = 0;
ans[1] = 0;
for (int i = 2; i <= len; i++){
ans[i] = Math.min(ans[i-2] + cost[i-2], ans[i-1] + cost[i-1]);
}
return ans[len];
}
}
执行用时:1 ms, 在所有 Java 提交中击败了92.05%的用户
内存消耗:38 MB, 在所有 Java 提交中击败了73.31%的用户
- 滚动数组
class Solution {
public int minCostClimbingStairs(int[] cost) {
int ans = 0, pre = 0, temp = 0;
for (int i = 2; i <= cost.length; i++){
temp = ans;
ans = Math.min(ans + cost[i-1], pre + cost[i-2]);
pre = temp;
}
return ans;
}
}
执行用时:1 ms, 在所有 Java 提交中击败了92.05%的用户
内存消耗:37.9 MB, 在所有 Java 提交中击败了90.69%的用户