LeetCode 107 Permutations
来源:互联网 发布:子域名查询工具 编辑:程序博客网 时间:2024/05/26 02:52
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].
分析:
全排列问题,这是两道题里第一道,即没有重复元素的全排列。
回溯问题,DFS。
具体思路是:
尝试将数组的每一个元素放在第一个位置,然后再对后面的元素进行全排列,这样就可以列出所有情况。
public class Solution { public List<List<Integer>> permute(int[] num) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if(num == null || num.length==0) return res; dfs(res, num, 0); return res; } private void dfs(List<List<Integer>> res, int[] num, int start){ //当后面没有元素的时候,递归搜索结束,这时候num数组里存放的就是一个排列 if(start == num.length){ res.add(arrayToList(num)); return; } for(int i=start; i<num.length; i++){ //尝试将所有元素放在第一个位置 swap(num, start, i); //递归得对后面元素全排列 dfs(res, num, start+1); //恢复现场 swap(num, start, i); } } private List arrayToList(int[] num){ List<Integer> list = new ArrayList<Integer>(); for(int i=0; i<num.length; i++){ list.add(num[i]); } return list; } private void swap(int[] num, int index1, int index2){ int temp = num[index1]; num[index1] = num[index2]; num[index2] = temp; }}
0 0
- LeetCode 107 Permutations
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- LeetCode: Permutations
- LeetCode: Permutations
- [Leetcode] Permutations
- [LeetCode] Permutations
- Leetcode: Permutations
- [Leetcode] Permutations
- [Leetcode] Permutations
- [LeetCode]Permutations
- LeetCode-Permutations
- [leetcode] permutations
- LeetCode - Permutations
- Leetcode: Permutations
- 【leetcode】Permutations
- FREEMARKER标签
- C++ 下 Function 对象的实现
- matlab函数详解之“sub2ind”
- NSString彻底去除空格的方法
- Charles(最强大的http调试工具)详细教程(上)
- LeetCode 107 Permutations
- Given two (dictionary) words as Strings, determine if they are isomorphic
- 使用jQuery使Div居中
- iOS 关于tableView cell的分割线的一些设置
- Linux下各文件夹的含义
- VP2.0中的纹理动画设计
- nginx 相关
- 黑马程序员——面向对象(二)---类的继承、多态性、匿名内部类、异常、包、访问控制、命名规范、jar文件
- STM32的BootLoader 从SD卡更新固件