forked from aswinkumarrk/data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutations.java
More file actions
36 lines (30 loc) · 1.01 KB
/
Permutations.java
File metadata and controls
36 lines (30 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.leetcode.problems.medium;
import java.util.ArrayList;
import java.util.List;
/**
* @author neeraj on 06/10/19
* Copyright (c) 2019, data-structures.
* All rights reserved.
*/
public class Permutations {
public static void main(String[] args) {
System.out.println(permute(new int[]{1, 2, 3}));
}
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
permuteUtil(nums, new ArrayList<>(), result);
return result;
}
private static void permuteUtil(int[] nums, List<Integer> current, List<List<Integer>> all) {
if (current.size() == nums.length) {
all.add(new ArrayList<>(current));
return;
}
for (int i = 0; i < nums.length; i++) {
if (current.contains(nums[i])) continue;
current.add(nums[i]); // Choose
permuteUtil(nums, current, all); // Explore
current.remove(current.size() - 1); // Un-choose
}
}
}