how to promise its the longest sequence?


  • 0
    S
    public List<String> findItinerary(String[][] tickets) {
            List<String> result = new ArrayList();
            Map<String, ArrayList<String>> graph = new HashMap();
            for(int i=0; i<tickets.length; i++){
                if(!graph.containsKey(tickets[i][0])){
                    ArrayList<String> adj = new ArrayList();
                    adj.add(tickets[i][1]);
                    graph.put(tickets[i][0], adj);
                }else{
                     graph.get(tickets[i][0]).add(tickets[i][1]);
                }
            }
            for(ArrayList<String> a : graph.values()){
                Collections.sort(a);
            }
            backtracing(result, "JFK", graph);
            return result;
        }
    
        public void backtracing(List<String> result, String current, Map<String, ArrayList<String>> graph){
            while(graph.containsKey(current) && !graph.get(current).isEmpty()){
                String s = graph.get(current).remove(0);
                backtracing(result, s, graph);
            }
            result.add(0,current); // the most important line 
        }
    

    This piece of code could pass all the test. I am just wondering how could it promise that its the longest sequence?
    if I move the code result.add(current); // the most important line inside the while loop, it will not pass the test, why?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.