File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ package AlgoExpert_Medium ;
2
+
3
+ import java .util .List ;
4
+
5
+ import java .util .ArrayList ;
6
+
7
+ public class Permutations {
8
+
9
+ public static void main (String [] args ) {
10
+ List <Integer > array = new ArrayList <>() ;
11
+ array .add (1 ) ; array .add (2 ) ; array .add (3 ) ;
12
+ System .out .println ( getPermutations ( array ) ) ;
13
+ }
14
+
15
+ public static List <List <Integer >> getPermutations (List <Integer > array ) {
16
+
17
+ if (array .isEmpty ()) {
18
+ return new ArrayList <List <Integer >>() ;
19
+ }
20
+
21
+ List <List <Integer >> list = new ArrayList <List <Integer >>() ;
22
+
23
+ List <Integer > current = new ArrayList <>() ;
24
+
25
+ return permutations (array , current , list ) ;
26
+
27
+ }
28
+
29
+ public static List <List <Integer >> permutations ( List <Integer > array , List <Integer > current , List <List <Integer >> list ) {
30
+
31
+ if (current .size () == array .size ()) {
32
+ List <Integer > added = new ArrayList <>(current ) ; // Imp to use new operator as current will be overwritten in subsequent calls.
33
+ list .add (added );
34
+ return list ;
35
+ }
36
+
37
+
38
+ for (int i =0 ; i <array .size (); i ++) {
39
+
40
+ int currentNumber = array .get (i ) ;
41
+
42
+ if (!current .contains (currentNumber )) { // Constraints.
43
+
44
+ current .add (currentNumber ) ; // Choose
45
+
46
+ permutations (array , current , list ) ; // Explore
47
+
48
+ current .remove (current .size ()-1 ) ; // Unchoose
49
+
50
+ }
51
+
52
+ }
53
+
54
+
55
+ return list ;
56
+
57
+ }
58
+ }
You can’t perform that action at this time.
0 commit comments