Can anyone help me with my java code?


  • 0
    C
    private List<String> result=new ArrayList<>();
    private int result_length;
    public List<String> findItinerary(String[][] tickets) {
       this.result_length=tickets.length+1;
       Map<String,List<String>> map=new HashMap<>();
       for(int i=0;i<tickets.length;i++){
           if(map.containsKey(tickets[i][0])) map.get(tickets[i][0]).add(tickets[i][1]);
           else {
               List<String> temp=new ArrayList<>();
               temp.add(tickets[i][1]);
               map.put(tickets[i][0],temp);
           }
       }
       for(String head:map.keySet()){
           List<String> temp=new ArrayList<>();
           temp.add(head);
           DFS(head,map,temp);  
       }
       return result;
       
    }
    public void DFS(String headKey,Map<String,List<String>> map,List<String> list){
        if(!map.containsKey(headKey)||map.get(headKey).isEmpty()){
            System.out.println(list.toString());
            if(list.size()!=result_length)  return;
            result=compareList(list,result);
            return;
        }
        for(int i=0;i<map.get(headKey).size();i++){
            List<String> temp=new ArrayList<>(map.get(headKey));//original
            String head=map.get(headKey).remove(i);
            List<String> temp1=new ArrayList<String>(list);
            temp1.add(head);
            DFS(head,map,temp1);
            map.put(headKey,temp);
        }
    }
    public List<String> compareList(List<String> list1, List<String> list2){
        if(list2.size()==0) return list1;
        for(int i=0;i<list1.size();i++){
            String a=list1.get(i);
            String b=list2.get(i);
            if(a.compareTo(b)==0) continue;
            if(a.compareTo(b)==1) return list2;
            return list1;
        }
        return list1;
    }
    

    I passed the example case, but I got time limit exceed in a complicated test case.
    I think the algorithm is right, can anyone help me to check if I'm right?


Log in to reply
 

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