publicvoidpermutation(int[] nums, int start){ if (start == nums.length - 1) { for (int i : nums) { //得到一个排列 System.out.print(nums); } } for (int i = start; i < nums.length; i++) { swap(nums, i, start); permutation(nums, start + 1); swap(nums, i, start); } } privatevoidswap(int[] nums, int a, int b){ int tmp = nums[a]; nums[a] = nums[b]; nums[b] = tmp; }
//放在Set中的数据类型必须实现Comparable接口的compareTo方法 Set<String> res = new TreeSet<>(); publicvoidpermutation2(int[] nums, int start){ if (start == nums.length - 1) { StringBuilder sb = new StringBuilder(); for (int i : nums) { sb.append(i); } res.add(sb.toString()); } for (int i = start; i < nums.length; i++) { //swap nums[i] nums[start] swap(nums, i, start); permutation2(nums, start + 1); //swap nums[i] nums[start] swap(nums, i, start); } } privatevoidswap(int[] nums, int a, int b){ int tmp = nums[a]; nums[a] = nums[b]; nums[b] = tmp; }