forked from 0Prashant21/Fest_2025
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutations.java
More file actions
32 lines (29 loc) · 994 Bytes
/
Permutations.java
File metadata and controls
32 lines (29 loc) · 994 Bytes
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
import java.util.*;
public class Permutations {
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
backtrack(nums, new boolean[nums.length], new ArrayList<>(), res);
return res;
}
private static void backtrack(int[] nums, boolean[] used, List<Integer> curr, List<List<Integer>> res) {
if (curr.size() == nums.length) {
res.add(new ArrayList<>(curr));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) continue;
used[i] = true;
curr.add(nums[i]);
backtrack(nums, used, curr, res);
curr.remove(curr.size() - 1);
used[i] = false;
}
}
public static void main(String[] args) {
int[] nums = {1, 2, 3};
List<List<Integer>> result = permute(nums);
for (List<Integer> perm : result) {
System.out.println(perm);
}
}
}