6
6
*
7
7
* Tags: Backtracking
8
8
*/
9
- class Astroid {
9
+ class Astroid01 {
10
+
10
11
public static void main (String [] args ) {
11
- Astroid a = new Astroid ();
12
+ Astroid01 a = new Astroid01 ();
12
13
System .out .println (a .astroid ("01*0*" ));
13
14
}
14
15
@@ -20,22 +21,22 @@ public List<String> astroid(String s) {
20
21
}
21
22
22
23
/**
23
- * Backtracking on the string
24
+ * Backtracking, generate all possible result
24
25
* Replace if current char is *
25
26
* Otherwise, go to next position
26
27
*/
27
28
public void astroid (String s , int pos , StringBuilder sb , List <String > res ) {
28
29
if (pos == sb .length ()) {
29
- res .add (sb .toString ());
30
+ res .add (sb .toString ()); // found a result
30
31
return ;
31
32
}
32
33
if (s .charAt (pos ) == '*' ) {
33
- sb .setCharAt (pos , '0' );
34
- astroid (s , pos + 1 , sb , res );
35
- sb .setCharAt (pos , '1' );
36
- astroid (s , pos + 1 , sb , res );
34
+ sb .setCharAt (pos , '0' ); // replace with 0
35
+ astroid (s , pos + 1 , sb , res ); // recurse
36
+ sb .setCharAt (pos , '1' ); // replace with 1
37
+ astroid (s , pos + 1 , sb , res ); // recurse
37
38
} else {
38
- astroid (s , pos + 1 , sb , res );
39
+ astroid (s , pos + 1 , sb , res );
39
40
}
40
41
}
41
42
}
0 commit comments