动态规划刷题笔记
53. Maximum Subarray
原题链接地址:https://leetcode.com/problems/maximum-subarray/description/
题目描述
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
题目分析
把原字符串分成很多不同的字串,然后求出字串中最大的。
把原字符串分成很多不同的字串,通过max(f+A[i],A[i])就可以搞定,如果之前的对我没贡献,还不如另起一个字串
设状态为 f[j],表示以 S[j] 结尾的最大连续子序列和,状态转移方程如下:
f=max(f+A[i],A[i]);//对于数组里的一个整数,它只有两种 选择:1、加入之前的 SubArray;2. 自己另起一个 SubArray。
maxsum=max(maxsum,f);// 求字串中最大的
算法设计
public int maxSubArray(int[] A) {
int n = A.length;
int[] dp = new int[n];//dp[i] means the maximum subarray ending with A[i];
dp[0] = A[0];
int max = dp[0];
for(int i = 1; i < n; i++){
dp[i] = A[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
max = Math.max(max, dp[i]);
}
return max;
}
另外一种算法设计:
public int maxSubArray(int[] A) {
int max = A[0], dp = A[0];
for (int i = 1; i < A.length; i++) {
dp = Math.max(dp + A[i] ,A[i]);
max = Math.max(max, dp);
}
return max;
}
第三种算法设计:
class Solution {
public:
int maxSubArray(int A[], int n) {
if(0==n) return 0;
int f=0;//f[j],表示以 A[j] 结尾的最大连续子序列和
int maxsum=A[0];
for(int i=0;i<n;++i)
{
f=max(f+A[i],A[i]);//是否需要另起一个字串,如果之前的对我没贡献,还不如另起一个字串。
maxsum=max(maxsum,f); //字串中最大的
}
return maxsum;
}
};
85.Maximal Rectangle
题目链接:https://leetcode.com/problems/maximal-rectangle/description/
题目描述
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
算法设计
public class Solution {
public int maximalRectangle(char[][] matrix) {
int area = 0, new_area, r, l;
if(matrix.length > 0){
int[] line = new int[matrix[0].length];
boolean[] is_processed = new boolean[matrix[0].length];
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[i].length; j++){
if (matrix[i][j] == '1') {
line[j]++;
is_processed[j] = false;
} else {
line[j] = 0;
is_processed[j] = true;
}
}
for(int j = 0; j < matrix[i].length; j++){
if(is_processed[j]) continue;
r = l = 1;
while((j + r < line.length)&&(line[j + r] >= line[j])){
if(line[j + r] == line[j]) is_processed[j + r] = true;
r++;
}
while((j - l >= 0)&&(line[j - l] >= line[j])) l++;
new_area = (r + l - 1)*line[j];
if (new_area > area) area = new_area;
}
}
} return area;
}
}
97.Interleaving String
题目链接:https://leetcode.com/problems/interleaving-string/description/
题目描述
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = “aabcc”,
s2 = “dbbca”,
When s3 = “aadbbcbcac”, return true.
When s3 = “aadbbbaccc”, return false.
题目分析
分析:判断字符串s3是否由s1,s2交叉存取组成
public boolean isInterleave(String s1, String s2, String s3) {
if ((s1.