LeetCode 第46,47题(Permutations)Java
来源:互联网 发布:基础软件服务经营范围 编辑:程序博客网 时间:2024/06/08 12:09
原题:Given a collection of distinct numbers, return all possible permutations.
第四十六题允许重复,四十七题不允许;
在解法上有相似的地方;
思路:这道全排列问题可以递归地去做,先确定一个值,对剩下的进行递归;
实际上是一道关于深度优先搜索算法的题目;
参考了这一篇博客:http://blog.csdn.net/chenchaofuck1/article/details/51194976
代码:
public class Solution { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> allLists=new LinkedList<>(); dfs(allLists,nums,0); return allLists; } void dfs(List<List<Integer>> Lists,int[] nums,int s){ if(s==nums.length){ List<Integer> list=new LinkedList<>(); for(int i=0;i<nums.length;i++){ //将一个排好序的序列存储起来; list.add(nums[i]); } Lists.add(list); }else{ for(int i=s;i<nums.length;i++){ boolean flag=false; //flag部分针对47题,在元素出现重复时不进行交换; for(int j=s;j<i;j++){ // if(nums[j]==nums[i]){ // flag=true; // } // } // if(flag){ // continue; // } // //交换两数字顺序; int tmp=nums[s]; nums[s]=nums[i]; nums[i]=tmp; dfs(Lists,nums,s+1); //交换回来; nums[i]=nums[s]; nums[s]=tmp; } } }}
利用flag去除重复的部分实际上是剪枝,将搜索树中一些值去除,不进行计算;
0 0
- LeetCode 第46,47题(Permutations)Java
- LeetCode第46题之 Permutations
- [leetcode-46]Permutations(java)
- LeetCode 46 Permutations + LeetCode 47 Permutations II
- LeetCode(46)Permutations
- Leetcode 46/47 Permutations, Permutations II
- leetcode 46-Permutations and 47-Permutations II
- 【leetcode】第46题 Permutations(递归法)题目+解析+代码
- [leetcode-47]Permutations II(java)
- LeetCode第47.题之Permutations II
- LeetCode- 46/47. Permutations/Permutations || (JAVA) (全排列1,2)
- LeetCode(47)Permutations II
- [Leetcode] Permutations (Java)w
- [Leetcode] Permutations II (Java)
- [LeetCode][Java] Permutations
- [LeetCode][Java] Permutations II
- (Java)LeetCode-46. Permutations
- [LeetCode-Java]46. Permutations
- <poj-2632>Crashing Robots
- html5 net XMLHttpRequest
- 并查集系列(一)——Social network connectivity
- Linux网络通信 -- TCP/IP协议
- Codeforces 401B Sereja and Contests【水题】
- LeetCode 第46,47题(Permutations)Java
- C语言编程注意事项
- [模板]康拓展开和他的逆运算
- Pillow学习之Image类(一)
- [Usaco06Dec] Cow Picnic
- signals linux
- hdu 5952 Counting Cliques(最大团思想+dfs)
- 线段树
- 复制alert内容,可对弹出的对话框文本进行复制