-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSubSeq.java
More file actions
59 lines (45 loc) · 1.53 KB
/
SubSeq.java
File metadata and controls
59 lines (45 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// print all subsequence of the given string
// give all subsets of the string
package RecursionBacktracking.level2;
import java.util.ArrayList;
public class SubSeq {
// in form of string
// but this take extra sapce
static void subSeqStr(String str) {
String resStr = new String();
helperSubSeqStr(str, resStr);
}
static void helperSubSeqStr(String str, String resStr) {
if (str.isEmpty()) {
System.out.println(resStr);
return;
}
char element = str.charAt(0);
// take that element
helperSubSeqStr(str.substring(1), resStr + element);
// not take that element
helperSubSeqStr(str.substring(1), resStr);
}
// in form of arraylist
static ArrayList<String> subSeqArrList(String str) {
String resStr = new String();
return helpersubSeqArrList(str, resStr);
}
static ArrayList<String> helpersubSeqArrList(String str, String resStr) {
if (str.isEmpty()) {
ArrayList<String> arr = new ArrayList<>();
arr.add(resStr);
return arr;
}
char element = str.charAt(0);
ArrayList<String> left = helpersubSeqArrList(str.substring(1), resStr + element);
ArrayList<String> right = helpersubSeqArrList(str.substring(1), resStr);
left.addAll(right);
return left;
}
public static void main(String[] args) {
String str = "abc";
// subSeqStr(str);
System.out.println(subSeqArrList(str));
}
}