Leetcode 647
Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).
Example 1:
Input: [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3.
Even though [1,3,5,7] is also an increasing subsequence, it’s not a continuous one where 5 and 7 are separated by 4.
1 | int findLengthOfLCIS(vector<int>& nums) { |
printLIS 路径
1 |
|
Leetcode 300
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
1 | int lengthOfLIS(vector<int>& nums) { |
复杂度:O(n^2)
解析:
https://www.youtube.com/watch?v=CE2b_-XfVDk
以下是O(nlogn)作法
1 |
|
dp[i]表示长度为i的LIS序列的最后一个数字最小末尾
https://www.cnblogs.com/ziyi--caolu/p/3227121.html
leetcode 53
Longest maximum subarray
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
1 |
|
方法二:
转移方程: dp[i] = nums[i]+(dp[i-1]>0?dp[i-1]:0);
1 |
|
拓展
给定K个整数的序列{ N1, N2, …, NK },其任意连续子序列可表示为{ Ni, Ni+1, …,
Nj },其中 1 <= i <= j <= K。最大连续子序列是所有连续子序列中元素和最大的一个,
例如给定序列{ -2, 11, -4, 13, -5, -2 },其最大连续子序列为{ 11, -4, 13 },最大和
为20。
在今年的数据结构考卷中,要求编写程序得到最大和,现在增加一个要求,即还需要输出该
子序列的第一个和最后一个元素。
http://acm.hdu.edu.cn/showproblem.php?pid=1231
1 | #include <iostream> |
关键是要找到子序列的第一个元素。
当找到最后一个元素的索引时候,从索引处由后往前找,知道sum等于结果的max,记录下此时的索引i,于是便找到了第一个元素的索引i
Longest common subsequence
转移方程 : res = max(lcs(i-1,j),lcs(i,j-1),1+lcs(i-1,j-1))
1 |
|
DP模板
1 | Dynamic programming formulation |
Traveling Salesman problem
TSP问题就是在一张有权图,从某个起点出发,然后go through each node exactly once and finally return to the beginning node,such that the weightSum is minimal
NP-HARD
no solution with dominomial time complexity
子问题一共有 2^n*n 个,每个子问题用O(n)复杂度来解决
T:(2^n*n^2)
0-1背包问题
状态转移方程:1
2
3
4
5//f[i][j]表示i个物品,容量j背包的物品最大价值
//若f[i][j] == f[i-1][j],说明不装第i个
//否则装入第i个,同时容量-w,价值+v,w,v分别为第i个物品的重量和价值
f[i][j] = max(f[i-1][j],f[i-1][j-w]+v);
kattis - knapsack
关键是如何打印出装入的物品的index
1 | int main(){ |
http://poj.org/problem?id=1579
记忆化搜索
把递归结果存在表里,减少不必要的递归次数
1 | int A[30][30][30]; |
dfs solve TSP
https://open.kattis.com/problems/beepers
dfs解TSP问题
基本思路是从出发点开始,尝试从出发点到其他所有点的可能性,然后回溯。
dfs的大概思路就是当n<num的时候,尝试到不同的点,回溯,当n==num的时候,比较现在的路径长度是否小于最短路径。
1 | int shortest,num; |
leetcode 931
minimum falling path sum
1 |
|
复杂度 n^2