1.Subarray Sum Equals K
Given an array of integers and an integer k,you need to find the total number of continuous subarrays whose sumequals to k.
最开始想法都是O(N)^2的思路即
for(intlow=0;low
如此进行计算,仔细考虑却是可以修成O(N)
2.Maximum Vacation Days
LeetCode wants to give one of its best employees theoption to travel among N cities to collect algorithm problems. Butall work and no play makes Jack a dull boy, you could takevacations in some particular cities and weeks. Your job is toschedule the traveling to maximize the number of vacation days youcould take, but there are certain rules and restrictions you needto follow.
- You can only travel among Ncities, represented by indexes from 0 to N-1. Initially, you are inthe city indexed 0 on Monday.
- The cities are connected byflights. The flights are represented as a N*N matrix (not necessarysymmetrical), called flights representing the airline status fromthe city i to the city j. If there is no flight from the city i tothe city j, flights[i][j] = 0; Otherwise, flights[i][j] = 1. Also,flights[i][i] = 0 for all i.
- You totally have K weeks (eachweek has 7 days) to travel. You can only take flights at most onceper day and can only take flights on each week’s Monday morning.Since flight time is so short, we don’t consider the impact offlight time.
- For each city, you can onlyhave restricted vacation days in different weeks, given an N*Kmatrix called days representing this relationship. For the value ofdays[i][j], it represents the maximum days you could take vacationin the city i in the week j.
You’re given the flights matrix and days matrix, andyou need to output the maximum vacation days you could take duringK weeks.
初始状态在第一周的第0个城市用dp[week][city]表示第week周第city城市的最长休假时间
递推为
dp[week][city] =Math.max(dp[week][city], dp[week -1][lastCity] + days[city][week -1]);
补贴一个优秀的代码:
public int maxVacationDays(int[][] flights, int[][] days) {
int n = flights.length;
int k = days[0].length;
int[][] dp = new int[k + 1][n];//k+1为传递链接中间节点需加1,n为状态位置不需添加1
for (int[] ints : dp) {
Arrays.fill(ints, Integer.MIN_VALUE / 2); //避免状态为改变时的0值判断
}
dp[0][0] = 0;
for (int week = 1; week <= k; week++) {
for (int city = 0; city < n; city++) {
for (int lastCity = 0; lastCity < n; lastCity++) {
if (city == lastCity || flights[lastCity][city] == 1) {
dp[week][city] = Math.max(dp[week][city],
dp[week - 1][lastCity] + days[city][week - 1]);
}
}
}
}
int answer = 0;
for (int i : dp[k]) {
answer = Math.max(answer, i);
}
return answer;
}
结:1.dp理解的深化。