Skip to content

Commit de00bfe

Browse files
Sanatan-ShrivastavaMohamad655
authored andcommitted
Created Permutations.java from Leetcode
Leetcode 46 : https://leetcode.com/problems/permutations/
1 parent bf3eb50 commit de00bfe

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

leetcode/Java/Permutations.java

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package BackTracking;
2+
import java.util.*;
3+
4+
/*
5+
Given a collection of distinct integers, return all possible permutations.
6+
7+
Example:
8+
9+
Input: [1,2,3]
10+
Output:
11+
[
12+
[1,2,3],
13+
[1,3,2],
14+
[2,1,3],
15+
[2,3,1],
16+
[3,1,2],
17+
[3,2,1]
18+
]
19+
*/
20+
public class Permutations {
21+
class Solution {
22+
public List<List<Integer>> permute(int[] nums) {
23+
List<List<Integer>> permutations = new ArrayList<>();
24+
boolean[] seen = new boolean[nums.length];
25+
if(nums == null || nums.length == 0) {
26+
return permutations;
27+
}
28+
findPermutations(nums, permutations, new ArrayList<>(), seen);
29+
return permutations;
30+
}
31+
32+
private void findPermutations (int[] nums, List<List<Integer>> permutations, List<Integer> current, boolean[] seen) {
33+
if(current.size() > nums.length) {
34+
return;
35+
}
36+
37+
if(current.size() == nums.length) {
38+
permutations.add(new ArrayList<>(current));
39+
return;
40+
}
41+
42+
for(int i = 0; i < nums.length; i++) {
43+
if(seen[i] == true) {
44+
continue;
45+
}
46+
current.add(nums[i]);
47+
seen[i] = true;
48+
findPermutations(nums, permutations, current, seen);
49+
current.remove(current.size() - 1);
50+
seen[i] = false;
51+
}
52+
53+
return;
54+
}
55+
}
56+
}

0 commit comments

Comments
 (0)