Skip to content

Commit 17612e7

Browse files
author
C5141506
committed
permutations leetcode 46
1 parent 3adaf6b commit 17612e7

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package java_problem.backtracking;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class Permutations {
7+
public static void main(String args[]) {
8+
int[] nums = new int[]{1, 2, 3};
9+
System.out.println(permute(nums));
10+
}
11+
12+
public static List<List<Integer>> permute(int[] nums) {
13+
List<List<Integer>> result = new ArrayList<>();
14+
int n = nums.length;
15+
if (n == 0) return result;
16+
for (int i = 0; i < n; i++)
17+
generatePermutation(nums, result, i, new ArrayList<>(), n);
18+
return result;
19+
}
20+
21+
public static void generatePermutation(int[] nums, List<List<Integer>> result, int index, List<Integer> ls, int n) {
22+
if (index == n && result.contains(ls)) return;
23+
if (index == n) {
24+
25+
if (ls.size() == n) {
26+
result.add(new ArrayList<>(ls));
27+
ls.remove(ls.size() - 1);
28+
}
29+
return;
30+
}
31+
for (int i = 0; i < n; i++) {
32+
if (!ls.contains(nums[i])) {
33+
ls.add(nums[i]);
34+
generatePermutation(nums, result, index + 1, ls, n);
35+
}
36+
}
37+
38+
if (ls.size() > 0)
39+
ls.remove(ls.size() - 1);
40+
}
41+
42+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package java_problem.backtracking;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class PermutationsApporoach2 {
7+
public static void main(String args[]) {
8+
int[] nums = new int[]{1, 2, 3};
9+
System.out.println(new PermutationsSolution().permute(nums));
10+
}
11+
}
12+
13+
class PermutationsSolution {
14+
15+
public List<List<Integer>> permute(int[] nums) {
16+
int n = nums.length;
17+
int totalPermutation = fact(n);
18+
List<Integer> ls = new ArrayList<>();
19+
for (int val : nums)
20+
ls.add(val);
21+
return findPermutation(totalPermutation, ls);
22+
}
23+
24+
public List<List<Integer>> findPermutation(int totalPermutation, List<Integer> ls) {
25+
List<List<Integer>> permutations = new ArrayList<>();
26+
for (int i = 0; i < totalPermutation; i++) {
27+
List<Integer> numbers = new ArrayList<Integer>(ls);
28+
int dividend = i;
29+
List<Integer> permutation = new ArrayList<Integer>();
30+
for (int divisor = ls.size(); divisor >= 1; divisor--) {
31+
int q = dividend / divisor;
32+
int r = dividend % divisor;
33+
permutation.add(numbers.get(r));
34+
numbers.remove(r);
35+
dividend = q;
36+
}
37+
permutations.add(permutation);
38+
}
39+
return permutations;
40+
}
41+
42+
public static int fact(int n) {
43+
if (n == 1) return n;
44+
return n * fact(n - 1);
45+
}
46+
}

0 commit comments

Comments
 (0)