|
| 1 | +package java_problem.dynamic_programming; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class NumberPermutation { |
| 6 | + public static void main(String[] args) { |
| 7 | + int[] nums = {1, 2, 3}; |
| 8 | + System.out.println(checkInclusion(nums)); |
| 9 | + } |
| 10 | + |
| 11 | + public static List<List<Integer>> checkInclusion(int[] nums) { |
| 12 | + int n = nums.length; |
| 13 | + int totalPermutation = fact(n); |
| 14 | + List<Integer> ls = new ArrayList<>(); |
| 15 | + for (int val : nums) |
| 16 | + ls.add(val); |
| 17 | + return findPermutation(totalPermutation, ls); |
| 18 | + } |
| 19 | + |
| 20 | + public static List<List<Integer>> findPermutation(int totalPermutation, List<Integer> ls) { |
| 21 | + List<List<Integer>> permutations = new ArrayList<>(); |
| 22 | + for (int i = 0; i < totalPermutation; i++) { |
| 23 | + List<Integer> numbers = new ArrayList<Integer>(ls); |
| 24 | + int dividend = i; |
| 25 | + List<Integer> permutation = new ArrayList<Integer>(); |
| 26 | + for (int divisor = ls.size(); divisor >= 1; divisor--) { |
| 27 | + int q = dividend / divisor; |
| 28 | + int r = dividend % divisor; |
| 29 | + permutation.add(numbers.get(r)); |
| 30 | + numbers.remove(r); |
| 31 | + dividend = q; |
| 32 | + } |
| 33 | + permutations.add(permutation); |
| 34 | + } |
| 35 | + return permutations; |
| 36 | + } |
| 37 | + |
| 38 | + public static int fact(int n) { |
| 39 | + if (n == 1) return n; |
| 40 | + return n * fact(n - 1); |
| 41 | + } |
| 42 | +} |
0 commit comments