Skip to content

Commit ea6354d

Browse files
committed
leetcode 46. permuations - backtracting
1 parent 67471f0 commit ea6354d

File tree

3 files changed

+108
-0
lines changed

3 files changed

+108
-0
lines changed

Backtracking/Permutations.java

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

LeetCode/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
## Backtracking
2828
- [x] [Subsets](https://github.com/kalpak92/DataStructures_Algorithms/tree/master/LeetCode/78.%20Subsets)
2929
- [x] [Subsets II](https://github.com/kalpak92/DataStructures_Algorithms/tree/master/LeetCode/80.%20Subsets%20II)
30+
- [x] [Permutations]()
3031

3132
## Linked List
3233

0 commit comments

Comments
 (0)