Only 1 test case is failing due to TLE . Can you help me , where should I optimize my code ?
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in) ;
String str = scan.next() ;
ArrayList<String> ans = new ArrayList<>() ;
permutations(str,"",ans) ;
Collections.sort(ans) ;
for(String val : ans){
System.out.println(val) ;
}
}
public static void permutations(String str , String ans , ArrayList<String> al){
if(str.length() == 1){
String res = ans+str;
if(!al.contains(res)){
al.add(res) ;
}
return ;
}
for(int i = 0 ; i < str.length() ; i ++){
permutations(str.substring(0,i)+str.substring(i+1) , ans+str.charAt(i) , al) ;
}
}
}