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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| public class Solution { public List<List<Integer>> permute(int[] nums) { Arrays.sort(nums); List<List<Integer>> list = new ArrayList<List<Integer>>(); int rht = nums.length - 1; int j = rht; list.add(toList(nums)); while(j >= 0) { j = rht; while(j-1 >=0 && nums[j] < nums[j-1])j--; if(j-1 < 0) return list; int i = j; while(i<=rht && nums[i] > nums[j-1]) i++; if(i>rht)i=rht+1; swap(nums, i-1, j-1); reverse(nums, j, rht); list.add(toList(nums)); } return null; } public void reverse(int[] nums, int i, int j) { int mid = (i+j)/2; if(mid==nums.length-1)return; if((i+j)%2==1) { for(int a = mid; a>=i;a--) { swap(nums, a, 2*mid-a+1); } }else { for(int a = mid-1; a>=i;a--) { swap(nums, a, 2*mid-a); } } } public List toList(int[] nums) { ArrayList<Object> arrayList = new ArrayList<>(); for(Integer e: nums) { arrayList.add(e); } return arrayList; } public void swap(int[] nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } public static void main(String[] args) { int[] nums = {2,6,1}; System.out.println(new Solution().permute(nums).toString()); } }
|