博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java for LeetCode 047 Permutations II
阅读量:4646 次
发布时间:2019-06-09

本文共 1738 字,大约阅读时间需要 5 分钟。

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], and [2,1,1].

解题思路一:

发现自己想多了,代码直接拿来用,结果Time Limit Exceeded!看来还是不能直接用

解题思路二:

修改上述代码,去掉set,改用List,修改如下:

static public List
> permuteUnique(int[] nums) { ArrayList
> set=new ArrayList
>(); dfs(set,nums,0); return set; } static List
list=new ArrayList
(); static public void dfs(List
> set,int[] nums,int depth){ if(depth==nums.length){ set.add(new ArrayList
(list)); return; } for(int i=0;i<=depth;i++){ while(i

 结果还是Time Limit Exceeded!看来不排序直接DFS这条路是走不通了。

解题思路三:

既然不排序直接DFS走不通,因此,可以考虑排序后,然后以字典的方式进行全排列添加,考虑到在题目中,我们已经写了一个字典的排列,稍作修改,添加boolean类型的返回值即可拿来用,JAVA实现如下:

static public List
> permuteUnique(int[] nums) { ArrayList
> set=new ArrayList
>(); Arrays.sort(nums); do{ List
list=new ArrayList
(); for(int num:nums) list.add(num); set.add(list); }while(nextPermutation(nums)); return set; } static public boolean nextPermutation(int[] nums) { int index = nums.length - 1; while (index >= 1) { if (nums[index] > nums[index - 1]) { int swapNum=nums[index-1],swapIndex = index+1; while (swapIndex <= nums.length - 1&& swapNum < nums[swapIndex]) swapIndex++; nums[index-1]=nums[swapIndex-1]; nums[swapIndex-1]=swapNum; reverse(nums,index); return true; } index--; } reverse(nums,0); return false; } static void reverse(int[] nums,int swapIndex){ int[] swap=new int[nums.length-swapIndex]; for(int i=0;i

 结果Accepted!

转载于:https://www.cnblogs.com/tonyluis/p/4504291.html

你可能感兴趣的文章
蓝桥杯 矩阵乘法 模板
查看>>
iOS_SourceTree忽略CocoaPods文件
查看>>
Unity编程标准导引-3.4 Unity中的对象池
查看>>
SETUP基础知识
查看>>
cocosstudio csd文件解析为.lua
查看>>
novoton-timer使用
查看>>
Perl Poetry .
查看>>
python基础0
查看>>
fs包报错, you can run: npm install --save fs
查看>>
Guice Provider绑定
查看>>
进程和线程区别
查看>>
UE4入门学习2:工程结构分析
查看>>
[Office]PPT 2013如何设置图片为半透明?
查看>>
个人技术博客
查看>>
Windows 2003 Server安全配置完整篇
查看>>
inform表单验证,正则表达式,用户名,身份证,密码,验证码
查看>>
CSS圆角
查看>>
安装 Apache Commons Logging API步骤
查看>>
返回顶部
查看>>
Log4cplus <1> 编译
查看>>