Permutations II 



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].

思路:这题相比于上一题,是去除了反复项。

代码上与上题略有区别。详细代码例如以下:

public class Solution {
boolean[] b;
List<List<Integer>> list;
Set<String> al;
public List<List<Integer>> permuteUnique(int[] nums) {
b = new boolean[nums.length];
Arrays.fill(b,true);
Arrays.sort(nums);
list = new ArrayList<List<Integer>>();
al = new HashSet<String>();
count(nums, "", nums.length);
//对al数据进行处理
Iterator<String> iterator = al.iterator();
//迭代器
while(iterator.hasNext()){
String s = iterator.next();
List<Integer> newal = new ArrayList<Integer>();
for(int i = 0; i < s.length();i++){
if(s.charAt(i) == '-'){//有负号
newal.add('0' - s.charAt(++i) );
}else{//无负号
newal.add(s.charAt(i) - '0');
}
}
list.add(newal);
}
return list;
}
/**
* @param nums 要排列的数组
* @param str 已经排列好的字符串
* @param nn 剩下须要排列的个数,假设须要全排列,则nn为数组长度
*/
void count(int[] nums,String str,int nn){
if(nn == 0){
al.add(str);//先加入到al中,再对al数据进行处理
return;
}
for(int i = 0; i < nums.length; i++){
if(nn == nums.length && i > 0 && nums[i] == nums[i-1]){
continue;//去除反复项
}
if(b[i]){//假设还没有组合,则组合上
b[i] = false;//标记为已组合
count(nums,str + nums[i],nn-1);
b[i] = true;//为下一组合准备
}
}
}
}

可是上述代码在数据量比較大的时候效率非常低,如数据有10个数据时大概耗时200ms。在论坛上看到了一个大神的代码。10个数据的耗时约25ms,效率非常高。

详细代码例如以下:

public class Solution {
public List<List<Integer>> permuteUnique(int[] num) {
List<List<Integer>> returnList = new ArrayList<List<Integer>>();
returnList.add(new ArrayList<Integer>()); for (int i = 0; i < num.length; i++) {
Set<List<Integer>> currentSet = new HashSet<List<Integer>>();
for (List<Integer> l : returnList) {
for (int j = 0; j < l.size() + 1; j++) {
l.add(j, num[i]);
List<Integer> T = new ArrayList<Integer>(l);
l.remove(j);
currentSet.add(T);
}
}
returnList = new ArrayList<List<Integer>>(currentSet);
} return returnList;
}
}

最新文章

  1. ubuntu16.04 + ubuntu + apache2 配置apache解析php
  2. Python 中的进程、线程、协程、同步、异步、回调
  3. PHP实现Restful风格的API
  4. mysql:mysql_query(): Unable to save result set
  5. 如何解决 Java 安全问题?
  6. Tomcat安装阿里云免费证书
  7. 把本地建好的项目提交到git上
  8. mfc窗口,父窗口parentwindow,所有者窗口ownerwindow 区别
  9. Eclipse怎么显示行号,定位某行
  10. js 指定位置插入html标签(可编辑div)
  11. Dstl Satellite Imagery Feature Detection-Data Processing Tutorial
  12. 前端入门20-JavaScript进阶之异步回调的执行时机
  13. jquery parents() next() prev() 找父级别标签 找同级别标签
  14. flink入门
  15. 云笔记项目-Spring事务学习_测试准备
  16. MVC与单元测试实践之健身网站(完)-备案与部署
  17. 第三方统计分析埋点工具对比,神策、Ptmind、GrowingIO、国双,还有谷歌分析,谁更好?
  18. 类名.class 与 类名.this 详解
  19. AngularJS 过滤器 Filter
  20. MVC实现加载更多

热门文章

  1. 洛谷P2168 荷马史诗 [NOI2015]
  2. 【CF1015F】Bracket Substring(字符串DP)
  3. 呵呵呵呵。。。系统还原了,终于可以用IE登陆百度了
  4. VUE 使用中踩过的坑
  5. 嵌入式Linux之我行——ARM MMU工作原理剖析【转】
  6. 处理printf的变参问题
  7. 修改linux 的bash 为zsh
  8. mac使用matplotlib
  9. Mysql同台机器主从配置
  10. hdu 2739(尺取法)