File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
datastructure-algorithm-java-examples/src/main/java/com/hellokoding/algorithm Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .hellokoding .algorithm ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .List ;
5+ import java .util .stream .Collectors ;
6+
7+ public class BackTracking_StringPermutations {
8+ List <String > result = new ArrayList <>();
9+
10+ String swap (String str , int i , int j ) {
11+ char [] arr = str .toCharArray ();
12+
13+ char temp = arr [i ];
14+ arr [i ] = arr [j ];
15+ arr [j ] = temp ;
16+
17+ return String .valueOf (arr );
18+ }
19+
20+ void enumerate (String str , int startIndex ) {
21+ if (startIndex == str .length ()-1 ) {
22+ result .add (str );
23+ return ;
24+ }
25+
26+ for (int i =startIndex ; i <str .length (); i ++) {
27+ str = swap (str , startIndex , i );
28+ enumerate (str , startIndex +1 );
29+ str = swap (str , startIndex , i ); // backtracking
30+ }
31+ }
32+
33+ public static void main (String [] args ) {
34+ String str = "ABC" ;
35+
36+ BackTracking_StringPermutations permutations = new BackTracking_StringPermutations ();
37+ permutations .enumerate (str , 0 );
38+
39+ System .out .println (permutations .result .stream ().collect (Collectors .joining (" " )));
40+ }
41+ }
You can’t perform that action at this time.
0 commit comments