【Leetcode】46. Permutations【DFS】
来源:互联网 发布:淘宝描述页图片尺寸 编辑:程序博客网 时间:2024/05/16 09:52
46. Permutations
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]]
分析:
用的DFS。
注意:
1、传的是引用变量,每次递归对同一个数组进行操作,递归的返回值为空。
2、ans为引用变量,不能直接将ans加入结果集。
代码:
public class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> ret = new ArrayList<List<Integer>>(); List<Integer> ans = new ArrayList<Integer>(); boolean visited[] = new boolean[nums.length]; if(nums.length == 0 || nums == null) return ret; for(int i = 0 ; i < nums.length ; i++) visited[i] = false; DFS(ret,nums,visited,ans); return ret; } private void DFS(List<List<Integer>> ret , int[] nums , boolean[] visited , List<Integer> ans){ if( ans.size() == nums.length ){ List<Integer> tmp = new ArrayList<Integer>(ans); ret.add(tmp); } for(int i = 0 ; i < nums.length ; i++){ if(visited[i]) continue; visited[i] = true; ans.add(nums[i]); DFS(ret,nums,visited,ans); visited[i] = false; ans.remove(ans.size()-1); } }}
25 / 25 test cases passed.
Status: Accepted
Runtime: 4 ms
Submitted: 3 hours, 58 minutes ago
0 0
- LeetCode 46. Permutations DFS
- 【Leetcode】46. Permutations【DFS】
- [LeetCode]46. Permutations &&深搜DFS
- leetcode---permutations---dfs
- leetcode---permutations-ii---dfs
- LeetCode-46-Permutations(DFS)-Medium
- 【Leetcode】47. Permutations II 【DFS】
- 46. Permutations【LeetCode算法之旅之DFS】
- [LeetCode]Permutations(回溯&&DFS&&递归!!!!)
- [LeetCode]Permutations II(!!!!!DFS递归&&回溯)
- LeetCode-47-Permutations II(DFS/剪枝)-Medium
- [LeetCode]47. Permutations II && DFS及剪枝
- [LeetCode]46.Permutations
- LeetCode 46.Permutations
- 46. Permutations Leetcode Python
- LeetCode --- 46. Permutations
- [Leetcode] 46. Permutations
- [leetcode] 46.Permutations
- [SPOJ 687]字符串
- MFC中Combo_Box(下拉框)的用法
- 项目实战-PC端固态布局 之机票预订
- 环形缓冲区笔记
- 功能测试的方法
- 【Leetcode】46. Permutations【DFS】
- kuangbin高斯消元模板
- android原生拍照适配问题
- 跳表(SkipList)及ConcurrentSkipListMap源码解析
- HTML5浏览器本地存储
- gitflow分支管理模型
- Jmeter – CSV Data
- 软件工程——软件开发模型
- 应用跳转(Deep Link)