标签:
代码:
public class Solution { List<List<Integer>> resultList = new ArrayList<>(); boolean flag = false; public List<List<Integer>> permute(int[] nums) { int len = nums.length; if(len == 0) return resultList; Arrays.sort(nums); permute_array(nums, len); return resultList; } public void permute_array(int[] nums, int len){ if(flag) return; List<Integer> list = new ArrayList<>(); for(int i = 0; i < nums.length; i++) list.add(nums[i]); resultList.add(list); int maxIndex = len - 1, minIndex = len -1; int max = nums[maxIndex]; int min = nums[minIndex]; for(int i = len-1; i>=0; i--){ if(nums[i] < min){ nums[minIndex] = nums[i]; nums[i] = min; permute_array(nums, len); } if(nums[i] < max){ int j = maxIndex; while(j >= 1 && nums[i] < nums[j-1]) j--; int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; permute_array(nums, len); } else{ if(i == 0) flag = true;; max = nums[i]; for(int j = i;j < len-1; j++) nums[j] = nums[j+1]; nums[len-1] = max; minIndex = i; maxIndex = len-1; } } } }
Jan 17 - Permutations; BackTracking; Array; Recursion;
标签:
原文地址:http://www.cnblogs.com/5683yue/p/5138588.html