46. Permutations

LeetCode

Approach 1: Backtracking

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> output = new LinkedList();

ArrayList<Integer> nums_lst = new ArrayList<Integer>();
for (int num : nums) nums_lst.add(num);

int n = nums.length;
backtrack(n, nums_lst, output, 0);
return output;
}

public void backtrack(int n,ArrayList<Integer> nums,List<List<Integer>> output,int first) {
if (first == n) output.add(new ArrayList<Integer>(nums));
for (int i = first; i < n; i++) {
Collections.swap(nums, first, i);
backtrack(n, nums, output, first + 1);
Collections.swap(nums, first, i);
}
}
}


Approach 2: using permutation generation -> Heap Algorithm

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
class Solution {
private void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
// Generating permutation using Heap Algorithm
private void heapPermutation(int[] arr, int n,List<List<Integer>> res) {
// if n becomes 1 then prints the obtained permutation
if (n == 1) {
ArrayList<Integer> ls=new ArrayList<>();
for(int i:arr) ls.add(i);
res.add(ls);
return;
}

for (int i = 0; i < n; i++) {
heapPermutation(arr, n - 1,res);

if (n % 2 == 1) { // if n is odd, swap first and last element
swap(arr, 0, n - 1);
} else { // If size is even, swap i-th and last element
swap(arr, i, n - 1);
}
}
}
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res=new ArrayList<>();
heapPermutation(nums,nums.length,res);
return res;
}
}

0%