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

Permutations

时间:2014-06-27 23:48:51      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   

题目

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].

方法

利用nextPermutation的思想,求解全部。http://blog.csdn.net/u010378705/article/details/31348875
	private boolean isReverseOrder(int[] num) {
		for (int i = 0; i < num.length - 1; i++) {
			if (num[i] < num[i + 1]) {
				return false;
			}
		}
		return true;
	}
    public List<List<Integer>> permute(int[] num) {
    	List<List<Integer>> list = new ArrayList<List<Integer>>();
    	if (num == null || num.length == 0) {
    		return list;
    	}
    	Arrays.sort(num);
    	while (!isReverseOrder(num)) {
    		List<Integer> subList = new ArrayList<Integer>();
    		for (int i = 0; i < num.length; i++) {
    			subList.add(num[i]);
    		}
    		list.add(subList);
    		nextPermutation(num);
    	}
    	List<Integer> subList = new ArrayList<Integer>();
		for (int i = 0; i < num.length; i++) {
			subList.add(num[i]);
		}
		list.add(subList);
		nextPermutation(num);
    	return list;
    }
	
    public void nextPermutation(int[] num) {
        if (num != null && num.length != 0 && num.length != 1) {
            int len = num.length;
            int i = len;
            for (; i > 1; i--) {
                if (num[i - 1] > num[i - 2]) {
                	
                	int flag = 0;
                	
                	for (int k = i - 1; k < len; k++) {
                		if (num[k] <= num[i - 2]) {
                			flag = k - 1;
                			break;
                		}
                	}
                	if (flag == 0) {
                		flag = len - 1;
                	}
                	int temp = num[flag];
                	num[flag] = num[i - 2];
                	num[i - 2] = temp;
                	Arrays.sort(num, i - 1, len);
                	break;
                }              
            }
        }
    }

Permutations,布布扣,bubuko.com

Permutations

标签:java   leetcode   

原文地址:http://blog.csdn.net/u010378705/article/details/35315659

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