leetcode解题方案--046--Permutations
来源:互联网 发布:java车位管理系统全套 编辑:程序博客网 时间:2024/06/05 08:53
题目
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的,觉得应该是种更好的方法。
阅读全文
0 0
- leetcode解题方案--046--Permutations
- leetcode解题方案--047--Permutations II
- [LeetCode]Permutations,解题报告
- 【LeetCode】Permutations 解题报告
- LeetCode-Permutations-解题报告
- [LeetCode] Permutations 解题报告
- Permutations [Leetcode 解题报告]
- leetcode 之 Permutations 解题思路
- 【LeetCode】Permutations II 解题报告
- [LeetCode] Permutations II 解题报告
- [leetcode] 46. Permutations 解题报告
- Permutations II [Leetcode 解题报告]
- LeetCode 46. Permutations 解题报告
- [Leetcode] 46. Permutations 解题报告
- [leetcode] 47. Permutations II 解题报告
- Leetcode # 46. Permutations 全排列 解题报告
- [Leetcode] 47. Permutations II 解题报告
- [leetcode]46. Permutations@Java解题报告
- LintCode解题记录 17.11.25 反转单链表
- 数据库双机热备份
- ThinkingInJava对this关键字的介绍
- 关于cellspacing、cellpadding属性问题
- 分布式事务一致性之三阶段提交
- leetcode解题方案--046--Permutations
- 使用Redis实现分布式锁及其优化
- 从零开始前端学习[55]:类型转换和Math方法
- 64位操作系统下运行debug
- 现代操作系统之进程与线程(上)
- 基础练习 完美的代价
- C#生成的应用程序版本如何修改
- css水平垂直居中三种实现方法
- 第一次使用这个网站,有关于vscode的问题想请教大家