-
Notifications
You must be signed in to change notification settings - Fork 6
/
PermutationsArray.java
47 lines (40 loc) · 1.19 KB
/
PermutationsArray.java
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
37
38
39
40
41
42
43
44
45
46
47
package com.shivaprasad.january.day26;
import java.util.ArrayList;
import java.util.List;
public class PermutationsArray {
public static void main(String[] args) {
int[] nums = {1,2,3};
List<List<Integer>> res = permute(nums);
for(List<Integer> r: res)
{
System.out.println(r);
}
}
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> ds = new ArrayList<>();
boolean freq[] = new boolean[nums.length];
recurPermute(nums,ds,ans,freq);
return ans;
}
private static void recurPermute(int[] nums, List<Integer> ds, List<List<Integer>> ans, boolean[] freq) {
if(ds.size() == nums.length)
{
ans.add(new ArrayList<>(ds));
return;
}
for(int i=0;i<nums.length;i++)
{
if(!freq[i])
{
freq[i] = true;
ds.add(nums[i]);
recurPermute(nums,ds,ans,freq);
ds.remove(ds.size() - 1);
freq[i] = false;
}
}
//T.C: O(n! * n)
//S.C: O(n) + O(n)
}
}