码迷,mamicode.com
首页 > 其他好文 > 详细

Jan 17 - Permutations; BackTracking; Array; Recursion;

时间:2016-01-18 11:52:15      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

代码:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!