个人记录-LeetCode 47. Permutations II
2016-12-14 20:22
507 查看
问题:
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
代码示例:
与LeetCode 46一样,采用全排列的方式即可:
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[ [1,1,2], [1,2,1], [2,1,1] ]
代码示例:
与LeetCode 46一样,采用全排列的方式即可:
public class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> result = new ArrayList<>(); if (nums == null || nums.length < 1) { return result; } //将数组排序,这样相同的数字排在一起,可以跳过,避免重复结果 Arrays.sort(nums); //flag记录一个数字是否被选择过 boolean[] flag = new boolean[nums.length]; //path记录每次排列的结果 List<Integer> path = new ArrayList<>(); //无脑暴力递归 permute(nums, path, flag, result); return result; } private void permute(int[] nums, List<Integer> path, boolean[] flag, List<List<Integer>> result) { //已经完成了所有位置的选择,返回结果 if (path.size() == nums.length) { result.add(path); return; } boolean first = true; //prev记录当前位置,上一次选择的数 int prev = -1; for (int i = 0; i < nums.length; ++i) { if (!flag[i]) { if (first) { prev = nums[i]; first = false; } else { //避免在同一个位置,选择相同的数,避免重复 if (nums[i] == prev) { continue; } prev = nums[i]; } //生成新的位图 List<Integer> tempList = new ArrayList<>(path); boolean[] tempFlag = new boolean[nums.length]; System.arraycopy(flag, 0, tempFlag, 0, nums.length); //添加本次信息 tempFlag[i] = true; tempList.add(nums[i]); //继续递归 permute(nums, tempList, tempFlag, result); } } } }
相关文章推荐
- scrapy使用
- 【java】事件与观察者模式
- arduino学习系列——串口通信
- linux下设置tomcat脚本启动
- Android 自定义View 之 触摸消息派发
- 其实没有以后
- Linux 命令行模式 你需要知道的那些事
- Android开发——ViewPage制作滑动导航界面
- MD 色板参考
- mysql数据库引擎及区别
- tomcat管理页面登陆问题
- spring mvc超强的json支持,你自己根本不需要额外的配置。spring mvc都给你配置好了!!!
- 晕头转向的一天
- 数据结构课程总结
- mcgs在win7在安装中途提示无法取得管理员权限,不能安装的错误
- 我的Android进阶之旅------>解决:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
- spring中的@resource等的区别
- 单调队列ssl2521数数
- 用pandas和numpy创建DataFrame
- C++类的DLL,C++静态调用。