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

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

原题链接在这里:

题目:

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

For example,

If nums = [1,2,2], a solution is:

[  [2],  [1],  [1,2,2],  [2,2],  [1,2],  []]

题解:

是的进阶版本。这里有duplicates, e.g. [1,2,2]但是res中不能包含两个[2].

还是backtracking, 注意去重.

Time Complexity: exponential. Space: O(nums.length). stack space.

AC Java:

1 class Solution { 2     public List
> subsetsWithDup(int[] nums) { 3 List
> res = new ArrayList
>(); 4 Arrays.sort(nums); 5 dfs(nums, 0, new ArrayList
(), res); 6 return res; 7 } 8 9 private void dfs(int [] nums, int start, List
item, List
> res){10 res.add(new ArrayList
(item));11 for(int i = start; i
start && nums[i]==nums[i-1]){13 continue;14 }15 item.add(nums[i]);16 dfs(nums, i+1, item, res);17 item.remove(item.size()-1);18 }19 }20 }

也所以在elem加完新元素想要放回res之前,需要先判断res中是否含有这个elem, 若是没有可以加到res中,若是已经有了,就不可以加到res中.

Time Complexity: exponential. Space: O(res.size()).

AC Java:

1 public class Solution { 2     public List
> subsetsWithDup(int[] nums) { 3 List
> res = new ArrayList
>(); 4 if(nums == null || nums.length == 0){ 5 return res; 6 } 7 Arrays.sort(nums); 8 res.add(new ArrayList
()); 9 for(int i = 0; i
elem = new ArrayList
(res.get(j));13 elem.add(nums[i]);14 if(!res.contains(elem)){15 res.add(elem);16 }17 }18 }19 return res;20 }21 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4841900.html

你可能感兴趣的文章
【转】xmind8 破解激活教程
查看>>
Mysql用命令方式启动服务
查看>>
【贪心】codeforces A. Heidi and Library (easy)
查看>>
【leetcode】lower_bound
查看>>
跨站请求伪造(CSRF)
查看>>
EF Code First数据库映射规则及配置
查看>>
.Net StackFrame
查看>>
Qt 学习之路:视图选择 (QItemSelectionModel)
查看>>
QStyleFactory类参考
查看>>
linux 获取系统屏幕分辨率
查看>>
MySQL 数据库常用命令小结
查看>>
log4net使用记录
查看>>
The Django Book 2.0--中文版
查看>>
编译式安装MYSQL
查看>>
更快找到正确的机器学习算法
查看>>
pair work 附加题解法(张艺 杨伊)
查看>>
记录我发现的第一个关于 Google 的 Bug
查看>>
linq操作符:转换操作符
查看>>
ng-深度学习-课程笔记-2: 神经网络中的逻辑回归(Week2)
查看>>
正则表达式的搜索和替换
查看>>