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

LeetCode 46 Permutations (全排列)

时间:2016-08-18 14:34:51      阅读:84      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!