-
Notifications
You must be signed in to change notification settings - Fork 1
/
AllPermutationsOfSubsets.java
55 lines (47 loc) · 2.22 KB
/
AllPermutationsOfSubsets.java
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
/*
Given a string with no duplicate characters, return a list with all permutations of the string and all its subsets.
Examples
Set = “abc”, all permutations are [“”, “a”, “ab”, “abc”, “ac”, “acb”, “b”, “ba”, “bac”, “bc”, “bca”, “c”, “cb”, “cba”, “ca”, “cab”].
Set = “”, all permutations are [“”].
Set = null, all permutations are [].
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AllPermutationsOfSubsets {
public List<String> allPermutationsOfSubsets(String s) { // TC: e * n! * n, SC: n
List<String> res = new ArrayList<>();
if (s != null) dfs(0, s.toCharArray(), res);
return res;
}
private void dfs(int idx, char[] A, List<String> res) {
res.add(new String(A, 0, idx));
for (int i = idx; i < A.length; i++) {
if (i != idx) swap(A, i, idx);
dfs(idx + 1, A, res);
if (i != idx) swap(A, i, idx);
}
}
private void swap(char[] A, int l, int r) {
char ch = A[l];
A[l] = A[r];
A[r] = ch;
}
public static void main(String[] args) {
AllPermutationsOfSubsets aps = new AllPermutationsOfSubsets();
List<String> l1 = aps.allPermutationsOfSubsets("slu");
System.out.println(l1); // [, s, sl, slu, su, sul, l, ls, lsu, lu, lus, u, ul, uls, us, usl]
System.out.println(l1.size()); // 16
List<String> l2 = aps.allPermutationsOfSubsets("fast");
System.out.println(l2); // [, f, fa, fas, fast, fat, fats, fs, fsa, fsat, fst, fsta, ft, fts, ftsa, fta, ftas, a, af, afs, afst, aft, afts, as, asf, asft, ast, astf, at, ats, atsf, atf, atfs, s, sa, saf, saft, sat, satf, sf, sfa, sfat, sft, sfta, st, stf, stfa, sta, staf, t, ta, tas, tasf, taf, tafs, ts, tsa, tsaf, tsf, tsfa, tf, tfs, tfsa, tfa, tfas]
System.out.println(l2.size()); // 65
l2 = l2.subList(0, 8);
System.out.println(l2.size());
System.out.println(l2);
l2.subList(8, l2.size()).clear();
System.out.println(l2);
int target = 100, factor = 10;
System.out.println(target /= factor);
}
}