Modified DFS in which no edge is traversed twice
void dfs ( string node , int & k , string & A ) { for ( int i = 0 ; i < k ; ++ i ) { string str = node + A [ i ] ; if ( seen . find ( str ) == seen . end ( ) ) { seen . insert ( str ) ; dfs ( str . substr ( 1 ) , k , A ) ; edges . push_back ( i ) ; } } }