diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index 041a7f03..ceb64589 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -261,6 +261,43 @@ for (pairtarget : targets[result[result.size() - 1]]) ## 其他语言版本 ### java + +```java +class Solution { + private LinkedList res; + private LinkedList path = new LinkedList<>(); + + public List findItinerary(List> tickets) { + Collections.sort(tickets, (a, b) -> a.get(1).compareTo(b.get(1))); + path.add("JFK"); + boolean[] used = new boolean[tickets.size()]; + backTracking((ArrayList) tickets, used); + return res; + } + + public boolean backTracking(ArrayList> tickets, boolean[] used) { + if (path.size() == tickets.size() + 1) { + res = new LinkedList(path); + return true; + } + + for (int i = 0; i < tickets.size(); i++) { + if (!used[i] && tickets.get(i).get(0).equals(path.getLast())) { + path.add(tickets.get(i).get(1)); + used[i] = true; + + if (backTracking(tickets, used)) { + return true; + } + + used[i] = false; + path.removeLast(); + } + } + return false; + } +} +``` ```java class Solution {