leetcode解题方案--046--Permutations
2017-11-25 15:57
411 查看
题目
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]
]
分析
这道题我AC最快,时间复杂度最高,超越了0.44的人我用了之前一个求下一个全排列的方法,对于每一个数组求下一个全排,转成list,扔进return里
下面是代码。代码也是又臭又长
public static List<List<Integer>> permute(int[] nums) { List<List<Integer>> re = new LinkedList<List<Integer>>(); int length = nums.length; int totalNum = 1; while (length >= 1) { totalNum = totalNum*length; length--; } for (int i = 0; i<totalNum;i++) { List<Integer> aa = Arrays.stream(nums) .boxed() .collect(Collectors.toList()); re.add(aa); nextPermutation(nums); } return re; } public static void nextPermutation(int[] nums) { int index = -1; for (int i = nums.length - 1; i > 0; i--) { if (nums[i - 1] < nums[i]) { index = i - 1; break; } } if (index == -1) { Arrays.sort(nums); return; } int flag = nums[index]; int minIndex = index + 1; int min = nums[minIndex]; for (int i = index + 1; i < nums.length; i++) { if (nums[i] > flag && nums[i] < min) { min = nums[i]; minIndex = i; } } int tmp = nums[index]; nums[index] = nums[minIndex]; nums[minIndex] = tmp; int start = index + 1; if (start < nums.length - 1) { for (int i = start + 1; i < nums.length; i++) { int tmp1 = nums[i]; int j = i; while (j > start && tmp1 < nums[j - 1]) { nums[j] = nums[j - 1]; j--; } nums[j] = tmp1; } } }
AC之后我又想了想,正常应该怎么做,想到了下面这种方法:
list<list<Integer>>func(int[] nums){ //如果数组只有一个元素 if(。。) return new list<Integer>(只包含这一个元素) for(int i = 0; i<nums.length; i++) { int[]newnums = 原数组除掉nums[i]; list<list<Integer>> list = func(); //遍历list,在每个子list中加入nums[i] } return list; }
看到有人说可以用dfs的,觉得应该是种更好的方法。
相关文章推荐
- leetcode解题方案--025--Reverse Nodes in k-Group
- leetcode解题方案--153--Find Minimum in Rotated Sorted Array
- leetcode解题方案--004--MedianofTwoSortedArrays
- leetcode解题方案--077--combinations
- [LeetCode]题解(python):046-Permutations
- LeetCode解题报告—— Permutations & Permutations II & Rotate Image
- LeetCode 046 Permutations
- leetcode解题方案--020--Valid Parentheses
- leetcode解题方案--078--subsets
- leetcode解题方案--028--Divide Two Integers
- 【LeetCode】 046. Permutations
- leetcode解题方案--033--Search in Rotated Sorted Array
- leetcode解题方案--040-- CombinationSum
- leetcode解题方案--045-- Jump Game II
- leetcode解题方案--154--Find Minimum in Rotated Sorted Array II
- Java for LeetCode 046 Permutations
- leetcode解题方案--019--Remove the End of Node of List
- leetcode解题方案--068--Text Justification
- leetcode解题方案--016--3 sum closest
- leetcode解题方案--024--Swap Nodes in Pairs