forked from rpj911/LeetCode_algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutation.java
More file actions
92 lines (74 loc) · 2.75 KB
/
Permutation.java
File metadata and controls
92 lines (74 loc) · 2.75 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package Algorithms.permutation;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
public class Permutation {
public static void main(String[] strs) {
int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.printf("Test size:%d \n", num.length);
Stopwatch timer1 = new Stopwatch();
permute(num);
System.out
.println("Computing time with ArrayDeque used as Queue/Deque: "
+ timer1.elapsedTime() + " millisec.");
System.out.printf("Test size:%d \n", num.length);
Stopwatch timer2 = new Stopwatch();
permute2(num);
System.out
.println("Computing time with ArrayDeque used as Queue/Deque: "
+ timer2.elapsedTime() + " millisec.");
}
public static ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
if (num == null) {
return ret;
}
permuteHelp(num, ret, new LinkedHashMap<Integer, Integer>());
return ret;
}
public static void permuteHelp(int[] num, ArrayList<ArrayList<Integer>> ret, LinkedHashMap<Integer, Integer> set) {
if (set.size() == num.length) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (Integer i: set.keySet()){
list.add(i);
}
ret.add(list);
return;
}
int len = num.length;
for (int i = 0; i < len; i++) {
if (set.containsKey(num[i])) {
continue;
}
//path.add(num[i]);
set.put(num[i], 0);
permuteHelp(num, ret, set);
//path.remove(path.size() - 1);
set.remove(num[i]);
}
}
public static ArrayList<ArrayList<Integer>> permute2(int[] num) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
if (num == null) {
return ret;
}
ArrayList<Integer> path = new ArrayList<Integer>();
permuteHelp2(num, path, ret);
return ret;
}
public static void permuteHelp2(int[] num, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> ret) {
if (path.size() == num.length) {
ret.add(new ArrayList<Integer>(path));
return;
}
int len = num.length;
for (int i = 0; i < len; i++) {
if (path.contains(num[i])) {
continue;
}
path.add(num[i]);
permuteHelp2(num, path, ret);
path.remove(path.size() - 1);
}
}
}