Contest Review

来源:互联网 发布:汽车销售行业分析数据 编辑:程序博客网 时间:2024/06/05 19:01

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
       for(inthigh =low+1; high
      if((sum[high]-sum[low])== target)
      res++;
如此进行计算,仔细考虑却是可以修成O(N)
 for(int pos=0;pos
       sums+=nums[pos]; //由于按序,前面的遍历不影响后面的结果
       if(map.containsKey((sums-target)))
       res+=map.get(sums-target);
       map.put(sums,map.get(sums)+1);
       }

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.
  1. You can only travel among Ncities, represented by indexes from 0 to N-1. Initially, you are inthe city indexed 0 on Monday.
  2. 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.
  3. 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.
  4. 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理解的深化。
      2.沉迷优化不可自拔

Referencehttp://blog.csdn.net/u014688145/article/details/71023781

0 0
原创粉丝点击