Modified DFS in which no edge is traversed twice
static void dfs ( String node , int k , String A ) { for ( int i = 0 ; i < k ; ++ i ) { String str = node + A . charAt ( i ) ; if ( ! seen . contains ( str ) ) { seen . add ( str ) ; dfs ( str . substring ( 1 ) , k , A ) ; edges . add ( i ) ; } } }