首页 > 其他 > 详细

LeetCode 46 Permutations (全排列)

时间:2016-08-18 14:32:49      阅读:171      评论:0      收藏:0      [点我收藏+]

Given a collection of distinct 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],
  [3,2,1]
]


题目链接:https://leetcode.com/problems/permutations/

题目大意:求全排列

题目分析:求全排列的算法分为以下几步

1. 找最后一个升序的末尾位置pos1

2. 找在pos1 - 1后的最后一个大于它的数字位置pos2

3. 交换pos1 - 1和pos2位置的数

4. 对pos1及之后的数字从小到大排序

例如 1 5 2 4 3,pos1 = 3,pos2 = 4交换得1 5 3 4 2,pos1后排序得1 5 3 2 4

public class Solution {
    
    void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
    
    boolean nextPermutation(int[] nums, int len) {
        int pos1 = -1, pos2 = 0;
        for(int i = len - 1; i >= 1; i--) {
            if(nums[i] > nums[i - 1]) {
                pos1 = i;
                break;
            }
        }
        if(pos1 == -1) {
            return false;
        }
        for(int i = len - 1; i >= pos1; i--) {
            if(nums[i] > nums[pos1 - 1]) {
                pos2 = i;
                break;
            }
        }
        swap(nums, pos1 - 1, pos2);
        Arrays.sort(nums, pos1, len);
        return true;
    }
    
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> currentList;
        Arrays.sort(nums);
        int cnt = 0;
        int len = nums.length;
        do {
            currentList = new ArrayList<>();
            for(int i = 0; i < len; i++)
                currentList.add(nums[i]);
            ans.add(currentList);
        }while(nextPermutation(nums, len));
        return ans;
    }
}


LeetCode 46 Permutations (全排列)

原文:http://blog.csdn.net/tc_to_top/article/details/52238682

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!