写了一下第二题, 请大家看看有没有什么问题多多指教,time complexity我自己也搞不清楚 感觉是O(N^2)?
并且说一下 第一个条件canGoTo确实没有用上 因为假设timecost和points都必须给全了info- import java.util.*;
- public class HighestPointsUnderTimeLimit {
- public static int highestPoint;
- public static int limit;
- public static int getHighestPoint(List<List<Integer>> canGoTo, int[] points, int[][] timeCost, int timeLimit){
- highestPoint = 0;
- limit = timeLimit;
- Map<Integer, Map<Integer, int[]>> srcToDestPointsCost = new HashMap<>();
- for(int i = 0; i < timeCost.length; i++){
- int src = timeCost[i][0];
- int dest = timeCost[i][1];
- int cost = timeCost[i][2];
- int srcPoint = points[src];
- int destPoint = points[dest];
- int[] srcToDest = new int[]{destPoint, cost};
- int[] destToSrc = new int[]{srcPoint, cost};
- srcToDestPointsCost.computeIfAbsent(src, v -> new HashMap<>()).putIfAbsent(dest, srcToDest);
- srcToDestPointsCost.computeIfAbsent(dest, v -> new HashMap<>()).putIfAbsent(src, destToSrc);
- }
- LinkedList<Integer> currPath = new LinkedList<>();
- currPath.add(0);
- dfs(srcToDestPointsCost, 0, points[0], 0, true, currPath);
- return highestPoint;
- }
- private static void dfs(Map<Integer, Map<Integer, int[]>> srcToDestPointsCost, int start, int currPoints, int currTime, boolean isStart, LinkedList<Integer> currPath){
- if((start == 0 && !isStart && currTime <= limit)){
- System.out.println(Arrays.toString(currPath.toArray()));
- highestPoint = Math.max(highestPoint, currPoints);
- return;
- } else if(currTime > limit){
- return;
- }
- if(start == 0){
- isStart = false;
- }
- Map<Integer, int[]> nextStops = srcToDestPointsCost.get(start);
- for(Integer nextStart : nextStops.keySet()){
- int[] info = nextStops.get(nextStart);
- int newPoints = currPoints + info[0];
- int newTime = currTime + info[1];
- currPath.add(nextStart);
- dfs(srcToDestPointsCost, nextStart, newPoints, newTime, isStart, currPath);
- currPath.remove(nextStart);
- }
- }
- public static void main(String args[]) {
- List<List<Integer>> canGoTo = new ArrayList<>();
- Integer[] l1 = new Integer[]{1, 2, 3};
- Integer[] l2 = new Integer[]{3};
- canGoTo.add(Arrays.asList(l1));
- canGoTo.add(Arrays.asList(l2));
- int[] points = new int[]{5, 10, 3, 20};
- int[][] timeCost = new int[][]{{0, 1, 10}, {0, 2, 4}, {0, 3, 60}, {1, 3, 40}};
- int timeLimit = 90;
- System.out.println(getHighestPoint(canGoTo, points, timeCost, timeLimit));
- }
- }
复制代码 |