Leetcode-46. Permutations
来源:互联网 发布:怎么开通淘宝花呗支付 编辑:程序博客网 时间:2024/05/17 18:24
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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]]这个题目一开始还是想着用递归来做,复杂度O(n^2)Your runtime beats 18.68% of java submissions.
public class Solution { public List<List<Integer>> permute(int[] nums) { if(nums.length == 0) return new ArrayList<List<Integer>>(); List<List<Integer>> results = new ArrayList<List<Integer>>(); List<Integer> result = new ArrayList<Integer>(); if(nums.length == 1){ result.add(nums[0]); results.add(result); return results; } Arrays.sort(nums); List<Integer> stores = new ArrayList<Integer>(); for(int num : nums) stores.add(num); generateNext(stores,result,results); return results; } public void generateNext(List<Integer> stores,List<Integer> result, List<List<Integer>> results){ int length = stores.size(); if(length == 1) { result.add(stores.get(0)); results.add(new ArrayList<Integer>(result)); result.remove(new Integer(stores.get(0))); } else{ for(int i = 0 ; i < length ; i ++){ int number = stores.get(i); result.add(number); stores.remove(i); generateNext(new ArrayList<Integer>(stores),result,results); stores.add(i,number); result.remove(new Integer(number)); } } }}
0 0
- [LeetCode]46.Permutations
- LeetCode 46.Permutations
- 46. Permutations Leetcode Python
- LeetCode --- 46. Permutations
- [Leetcode] 46. Permutations
- [leetcode] 46.Permutations
- LeetCode 46. Permutations DFS
- 46. Permutations LeetCode
- Leetcode 46. Permutations
- leetcode 46. Permutations
- LeetCode *** 46. Permutations
- LeetCode 46. Permutations
- leetcode 46. Permutations
- LeetCode - 46. Permutations
- 【leetcode】46. Permutations
- leetcode 46. Permutations
- [LeetCode] 46. Permutations
- leetcode 46. Permutations
- sql中drop、truncate和delete的区别
- Git Windows Redmine服务端配置
- [写给女生的C语言][01]Hello World!
- Linux 下 Shell 命令的分类及用法
- Linear Algebra - Lesson 3. 乘法和逆矩阵
- Leetcode-46. Permutations
- 潜伏在无线网中的阴影——ARP欺骗获取任一设备浏览和接收的图片
- 怎么用git bash上传本地项目代码到您的github仓库1
- The Closest Pair Problem(UVa 10245) 计算几何+最近点对问题
- 137. Single Number II
- [Leetcode 375] Guess Number Higher or Lower II
- 在Python中利用Theano训练神经网络
- phpstorm2016汉化补丁2016.2版
- 36. Web 主机托管