Permutations 解答
2015-10-16 10:27
435 查看
Question
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].
Solution
Traditional backtracking way to solve this problem.public class Solution { public List<List<Integer>> permute(int[] nums) { Arrays.sort(nums); int length = nums.length; List<List<Integer>> result = new ArrayList<List<Integer>>(); boolean[] visited = new boolean[length]; dfs(nums, visited, new ArrayList<Integer>(), result); return result; } private void dfs(int[] nums, boolean[] visited, List<Integer> record, List<List<Integer>> result) { if (record.size() == nums.length) { if (!result.contains(record)) result.add(new ArrayList<Integer>(record)); return; } for (int i = 0; i < nums.length; i++) { if (!visited[i]) { record.add(nums[i]); visited[i] = true; dfs(nums, visited, record, result); // Restore record.remove(record.size() - 1); visited[i] = false; } } } }
相关文章推荐
- 使用 yum 安装 virtualbox 虚拟机
- css属性:hover
- subString的用法
- 用C#来调用cmd命令程序,实现wifi控制的工具
- Visual Studio 常用快捷键
- MVC 5.0(or5.0↓) Ajax.BeginForm 异步上传附件问题,答案是不能的!
- 如何比较代码框架?
- asp.net的加密解密技巧
- 9月国内网民地域分布TOP12:湖南与上海排名互换
- jquery EasyUI 心得--------2 datagrid中混用渲染方式引出的bug带给我的反思
- stat用法:获取文件对应权限的数字
- stat用法:获取文件对应权限的数字
- TCP与UDP协议
- android 界面控件的使用
- Oracle 10g RAC TAF介绍
- 所有界面锁定屏幕方向,某一个界面支持屏幕旋转~
- 【Android学习笔记】 画图
- Google translate API 调用方法
- struts2的namespace
- shell中可能经常能看到:>/dev/null 2>&1