LeetCode题解:Permutations
2015-09-06 21:14
197 查看
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,2个数中的位置中,插入前要把当前已完成组合复制
代码:
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,2个数中的位置中,插入前要把当前已完成组合复制
代码:
public class Solution { public List<List<Integer>> permute(int[] nums) { LinkedList<List<Integer>> result = new LinkedList<List<Integer>>(); result.add(new ArrayList<Integer>()); for(int n : nums){ for(int len = result.size(); len > 0; len--){ List<Integer> temp = result.pollFirst(); for(int j = 0; j <= temp.size(); j++){ List<Integer> newPermute = new ArrayList<Integer>(temp); newPermute.add(j, n); result.add(newPermute); } } } return result; } }
相关文章推荐
- HDU 4747 Mex
- Scala 深入浅出实战经典 第77讲:模式匹配下的提取器动手构造实战
- 1-1 Zabbix 监控安装
- 将系统中的编码输出到txt文件
- LeetCode_Tree_Populating Next Right Pointers in Each Node I II
- 一起talk C栗子吧(第四十七回:C语言实例--走迷宫一)
- FPGA/CPLD中如何实现低于一个时钟周期的延时?
- [dp](不连续)最大公共上升子序列 POJ 2127
- Android开发利器(Logcat 、DDMS、ADB)的使用
- 完美的运用MSComm控件开发串口调试助手
- 如何变成有趣的人?
- Linux系统里的加密压缩方式
- 文件乱码问题
- jquery中表单 多选框的一种巧妙写法
- c++string字符串的输出
- Sql Server中and和or的优先级问题
- HDU 2489 Minimal Ratio Tree(最小生成树)
- 程序1
- 【PHP】解决html网页乱码问题
- Migrate table to another Oracle Server-01