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; } }
时间: 2024-10-15 10:23:23