File tree 3 files changed +108
-0
lines changed
3 files changed +108
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Given a collection of distinct integers, return all possible permutations.
3
+ *
4
+ * Example:
5
+ * Input: [1,2,3]
6
+ * Output:
7
+ * [
8
+ * [1,2,3],
9
+ * [1,3,2],
10
+ * [2,1,3],
11
+ * [2,3,1],
12
+ * [3,1,2],
13
+ * [3,2,1]
14
+ * ]
15
+ */
16
+ import java .util .*;
17
+
18
+ class Permutations
19
+ {
20
+ public List <List <Integer >> permute (int [] nums ) {
21
+ List <List <Integer >> result = new ArrayList <>();
22
+
23
+ Arrays .sort (nums );
24
+
25
+ backtrack (result , new ArrayList <>(), nums );
26
+
27
+ return result ;
28
+ }
29
+
30
+ public void backtrack (List <List <Integer >> result , List <Integer > temp , int [] nums )
31
+ {
32
+ if (temp .size () == nums .length )
33
+ result .add (new ArrayList <>(temp ));
34
+ else
35
+ {
36
+ for (int i = 0 ; i < nums .length ; i ++)
37
+ {
38
+ if (temp .contains (nums [i ]))
39
+ continue ;
40
+
41
+ System .out .println (temp );
42
+
43
+ temp .add (nums [i ]);
44
+
45
+ backtrack (result , temp , nums );
46
+
47
+ temp .remove (temp .size () - 1 );
48
+ }
49
+ }
50
+ }
51
+
52
+ public static void main (String [] args ) {
53
+ Permutations obj = new Permutations ();
54
+
55
+ int [] nums = {1 ,2 ,3 };
56
+
57
+ System .out .println (obj .permute (nums ));
58
+ }
59
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Given a collection of distinct integers, return all possible permutations.
3
+ *
4
+ * Example:
5
+ * Input: [1,2,3]
6
+ * Output:
7
+ * [
8
+ * [1,2,3],
9
+ * [1,3,2],
10
+ * [2,1,3],
11
+ * [2,3,1],
12
+ * [3,1,2],
13
+ * [3,2,1]
14
+ * ]
15
+ */
16
+
17
+ class Solution {
18
+ public List <List <Integer >> permute (int [] nums ) {
19
+ List <List <Integer >> result = new ArrayList <>();
20
+
21
+ Arrays .sort (nums );
22
+
23
+ backtrack (result , new ArrayList <>(), nums );
24
+
25
+ return result ;
26
+ }
27
+
28
+ private void backtrack (List <List <Integer >> result , List <Integer > temp , int [] nums )
29
+ {
30
+ if (temp .size () == nums .length )
31
+ result .add (new ArrayList <>(temp ));
32
+ else
33
+ {
34
+ for (int i = 0 ; i < nums .length ; i ++)
35
+ {
36
+ if (temp .contains (nums [i ]))
37
+ continue ;
38
+
39
+ temp .add (nums [i ]);
40
+
41
+ backtrack (result , temp , nums );
42
+
43
+ temp .remove (temp .size () - 1 );
44
+ }
45
+ }
46
+ }
47
+ }
48
+
Original file line number Diff line number Diff line change 27
27
## Backtracking
28
28
- [x] [ Subsets] ( https://github.com/kalpak92/DataStructures_Algorithms/tree/master/LeetCode/78.%20Subsets )
29
29
- [x] [ Subsets II] ( https://github.com/kalpak92/DataStructures_Algorithms/tree/master/LeetCode/80.%20Subsets%20II )
30
+ - [x] [ Permutations] ( )
30
31
31
32
## Linked List
32
33
You can’t perform that action at this time.
0 commit comments