Skip to content

Commit cef6ffe

Browse files
authored
Create Permutations.java
1 parent b6ea686 commit cef6ffe

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Medium/Permutations.java

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy