public class Permutation { public staticList<List<Integer>> permute(int[] nums) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if (nums.length == 0) returnresult; while (true) { List<Integer> temp = new ArrayList<Integer>(); for (int t: nums) { temp.add(t); } result.add(temp); int i = nums.length - 2; while (i >= 0 && nums[i] > nums[i + 1]) i--; if (i < 0) break;
int j = nums.length - 1; while (j > i && nums[i] > nums[j]) j--; swap(nums, i, j); reverse(nums, i + 1, nums.length - 1); } reverse(nums, 0, nums.length - 1); returnresult; } public staticvoid swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } public staticvoid reverse(int[] nums, int begin, intend) { while (begin < end) { swap(nums, begin, end); begin++; end--; } }
public staticvoid main(String[] args) { int[] nums = {1, 2, 3, 4}; List<List<Integer>> result = permute(nums); for (List<Integer> list: result) { for (Integer i: list) { System.out.print(i); } System.out.println(""); } for (int i = 0; i < nums.length; i++) { System.out.print(nums[i] + " "); } } }