1. 剑指 Offer 42. 连续子数组的最大和
- (https://leetcode-cn.com/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof/)
- 本题关键在于dp[i]表示
class Solution {
public int maxSubArray(int[] nums) {
int max = nums[0];
int sum = nums[0];
for (int i = 1; i < nums.length; ++i) {
if (sum > 0) {
sum += nums[i];
}else {
sum = nums[i];
}
if (sum > max)
max = sum;
}
return max;
}
}
2. 面试题 08.01. 三步问题
- (https://leetcode-cn.com/problems/three-steps-problem-lcci/)
class Solution {
public int waysToStep(int n) {
int first = 1;
int second = 2;
int third = 4;
if(n == 1) return first;
else if (n == 2) return second;
else if (n == 3) return third;
else {
for(int i = 4; i <=n; ++i) {
int temp = third;
third = (int)((first + second + (long)third) % 1000000007);
first = second;
second = temp;
}
}
return third;
}
}
3. 300. 最长递增子序列
- (https://leetcode-cn.com/problems/longest-increasing-subsequence/)
- 这道题的动态规划算法还是挺难想(我是菜鸡)
- d p [ i ] dp[i]dp[i] 表示以第i ii个元素为结尾的递增子序列的最大长度。
- 状态转移方程:对于在第j jj个元素(j < i j < ij<i),如果存在n u m s [ j ] < n u m s [ i ] nums[j] < nums[i]nums[j]<nums[i],则d p [ i ] dp[i]dp[i] 至少为d p [ j ] + 1 dp[j] + 1dp[j]+1,至少的意思是说应该考虑所有的j jj元素,并从中区最大的d p [ j ] dp[j]dp[j]。
class Solution {
public int lengthOfLIS(int[] nums) {
int[] lens = new int[nums.length];
int max = lens[0] = 1;
for (int i = 1; i < nums.length; ++i) {
int t_len = 0;
for (int j = 0; j < i; ++j) {
if (nums[j] < nums[i] && lens[j] > t_len) {
t_len = lens[j];
}
}
lens[i] = t_len + 1;
if (max < lens[i]) max = lens[i];
}
return max;
}
}
版权声明:本文为sunshine2285原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。