【leetcode】第47题 Permutations II(非递归法)题目+解析+代码
来源:互联网 发布:淘宝指南针运动 编辑:程序博客网 时间:2024/06/06 03:40
【题目】
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]]【解析】
这个题和上一题几乎一样,这里使用非递归法解答,递归法参照第46题即可解答。
【代码】
public List<List<Integer>> permuteUnique(int[] nums) { LinkedList<List<Integer>> res = new LinkedList<List<Integer>>(); int n = nums.length; Arrays.sort(nums); List<Integer> temp = new ArrayList<Integer>(); for(int b:nums) temp.add(b); res.add(temp); while(true) { int count=-1; for(int i=n-1;i>0;i--) if(nums[i-1]<nums[i]) { count=i-1; break; } if(count==-1) return res; for(int i=n-1;i>count;i--) if(nums[i]>nums[count]) { swap(nums,count,i); break; } perm(nums,count+1,n-1); List<Integer> tempList = new ArrayList<Integer>(); for(int b:nums) tempList.add(b); res.add(tempList); } } public static void swap(int[] nums,int p,int q){ int temp=nums[p]; nums[p]=nums[q]; nums[q]=temp; } public static void perm(int[] nums,int p,int q){ for(int left=p,right=q;left<right;left++,right--) { int temp=nums[left]; nums[left]=nums[right]; nums[right]=temp; } }
阅读全文
0 0
- 【leetcode】第47题 Permutations II(非递归法)题目+解析+代码
- 【leetcode】第46题 Permutations(递归法)题目+解析+代码
- 【leetcode】第59题 Spiral Matrix II 题目+解析+代码
- LeetCode-47-Permutations II 递归+dict
- LeetCode第47.题之Permutations II
- 【leetcode】第63题 Unique Paths II 题目+解析+JAVA代码
- [leetcode 47] Permutations II
- leetcode || 47、 Permutations II
- leetcode 47 : Permutations II
- leetcode 47: Permutations II
- leetcode 47:Permutations II
- 【leetcode】【47】Permutations II
- LeetCode 47 - Permutations II
- 【LeetCode-47】Permutations II
- LeetCode 47 Permutations II
- Leetcode 47 Permutations II
- Leetcode 47 Permutations II
- LeetCode 47 Permutations II
- Jmeter接口测试-CSV参数化
- 【转载】leveldb之MANIFEST
- 如何做到防止SQL注入
- MySQL binlog相关分析
- Find the hotel(HDU-3193) (RMQ)
- 【leetcode】第47题 Permutations II(非递归法)题目+解析+代码
- VS项目-属性小技巧
- 安卓_动画
- Android逆向之smali注入
- VMware Workstation Pro 虚拟机安装系统注意事项
- 关于CDH页面下载HDFS文件地址解析出错
- git初步使用
- 关于win,linux下firefox以及谷歌内核浏览器网页播放视频的问题及解决方案
- Android实现黑白主题切换