46Permutations
来源:互联网 发布:伪装者好看吗 知乎 编辑:程序博客网 时间:2024/04/29 07:29
题目链接:https://leetcode.com/problems/permutations/
题目:
Given a collection of 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], and [3,2,1].
解题思路:
先叙述自己的思路:
1. 先把数组的元素都放到一个集合Set中去
2. for 循环遍历 Set 中的元素
3. 然后把去除当前元素的集合传入下一层递归,这样下一次选元素时就不包含上一轮已经遍历过的元素了
4. 直到 Set 大小为 1 时,就把最后一个元素放入列表中返回
5. 把当前轮元素分别加入到递归返回的众多列表中,形成的新列表又加入到本轮要返回的结果列表中
注:这样的算法实际是每轮都带着所有等待被挑选的元素进入下一轮递归,这对空间要求较大。并且在程序运行之初还要遍历整个数组,把所有元素都存到集合中,对时间的要求也比较多。
上网看到大牛更好的方法。每次递归不需要携带元素,只需要维护一个用来标记元素是否被访问过的数组,以及一个终极结果列表。当元素选择完后,对每一个结果都创建一个新列表将它们包含,再将这些列表分别放到终极列表中。
参考链接:http://blog.csdn.net/linhuanmars/article/details/21569031
自己思路的实现:
public class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList(); if(nums == null || nums.length == 0) return res; Set<Integer> set = new HashSet(); for(int i = 0; i < nums.length; i ++) set.add(nums[i]); return help(set); } List<List<Integer>> help(Set<Integer> set) { List<List<Integer>> res = new ArrayList(); if(set.size() == 1) { List<Integer> list = new ArrayList(); for(Integer k : set) list.add(k); res.add(list); return res; } for(Integer k : set) { Set<Integer> subSet = new HashSet(set); subSet.remove(k); List<List<Integer>> subList = help(subSet); for(List<Integer> l : subList) { l.add(k); res.add(l); } } return res; }}
25 / 25 test cases passed.Status: AcceptedRuntime: 288 ms
网络大牛思路的实现:
public class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList(); if(nums==null || nums.length==0) return res; helper(nums, new boolean[nums.length], new ArrayList<Integer>(), res); return res; } private void helper(int[] nums, boolean[] used, List<Integer> item, List<List<Integer>> res) { if(item.size() == nums.length) { res.add(new ArrayList<Integer>(item)); return; } for(int i=0;i<nums.length;i++) { if(!used[i]) { used[i] = true; item.add(nums[i]); helper(nums, used, item, res); item.remove(item.size()-1); used[i] = false; } } }}
25 / 25 test cases passed.Status: AcceptedRuntime: 268 ms
0 0
- 46 Permutations
- 46 Permutations
- 46Permutations
- [46]Permutations
- Permutations 46
- Leetcode 46/47 Permutations, Permutations II
- leetcode 46-Permutations and 47-Permutations II
- LeetCode 46 Permutations + LeetCode 47 Permutations II
- LeetCode 46: Permutations
- leetcode 46 Permutations
- LeetCode 46 Permutations II
- LeetCode(46) Permutations
- [leetcode 46] Permutations
- Leetcode NO.46 Permutations
- leetcode || 46、Permutations
- leetcode-46 Permutations
- leetcode 46 : Permutations
- Leetcode #46 Permutations
- 中国科大推出的研究生系列创新创业课程
- Ubuntu 14.04 LTS常见问题与配置
- Machine Learning--Andrew Ng--week 1
- 模式匹配算法
- 【Python爬虫】爬取成绩计算绩点
- 46Permutations
- ios 9 中 程序员需要注意的地方
- jquery中对dom元素的disabled属性的禁用和启用(removeAttr)
- Html5的学习之旅-Html5的web Storage概述(16)
- MongoDB学习7_mongodb查询语句与sql语句的对照
- Linux
- 蛇形填数
- TCHAR转String
- hrbust 1429