dfs 排列组合——找所有子集(重复元素和不重复元素)
17. 子集
给定一个含不同整数的集合,返回其所有的子集。
样例
样例 1:
输入:[0]
输出:
[
[],
[0]
]
样例 2:
输入:[1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
挑战
你可以同时用递归与非递归的方式解决么?
注意事项
子集中的元素排列必须是非降序的,解集必须不包含重复的子集。
时间复杂度是O(2^n),本质就是在做二叉树的dfs。[1,2,3]举例:
root
/ \
不选中1 选中1
/ \ / \
不选中2 选中2 不选中2 选中2
。。。。。
使用dfs记录遍历路径即可。
class Solution:
"""
@param nums: A set of numbers
@return: A list of lists
"""
def subsets(self, nums):
# write your code here
path, results = [],[]
self.helper(sorted(nums), 0, path, results)
return results def helper(self, nums, index, path, results):
if index == len(nums):
results.append(list(path))
return path.append(nums[index])
self.helper(nums, index+1, path, results) path.pop()
self.helper(nums, index+1, path, results)
第二种写法是使用位运算,也比较直观,代码很容易写出来:
class Solution:
"""
@param nums: A set of numbers
@return: A list of lists
"""
def subsets(self, nums):
# write your code here
nums = sorted(nums)
n = len(nums)
results = []
for i in range(1<<n):
results.append(self.get_num(nums, i, n))
return results def get_num(self, nums, num, cnt):
result = []
for i in range(cnt):
if num & (1<<i):
result.append(nums[i])
return result
第三种写法是使用for dfs写法,看下面的图,以【1,2,3】为例:
root (path=[])
|
----------------------------------------
| | |
1 2 3
/ \ |
2 3 3
/
3
在遍历上述树的过程中将path全部记录下来(path不用走到叶子节点):
class Solution:
"""
@param nums: A set of numbers
@return: A list of lists
"""
def subsets(self, nums):
# write your code here
nums = sorted(nums)
path, result = [], []
self.dfs(nums, 0, path, result)
return result def dfs(self, nums, index, path, result):
result.append(list(path)) if index == len(nums):
return for i in range(index, len(nums)):
path.append(nums[i])
self.dfs(nums, i+1, path, result)
path.pop()
含有重复元素的子集问题,例如【1,2,2,3】
root (path=[])
|
----------------------------------------
| | | |
1 2 2(重复) 3
/ \ / \ |
2 3 2 3 3
/ \ |
2 3 3
|
3
又例如【1,1,2,3】
root (path=[])
|
----------------|-------------------------
| 1(重复) | |
1 / \ 2 3
/ | \ 2 3 |
1 2 3 | 3
/ \ | 3
2 3 3
|
3
所以代码如下:
class Solution:
"""
@param nums: A set of numbers.
@return: A list of lists. All valid subsets.
"""
def subsetsWithDup(self, nums):
# write your code here
nums = sorted(nums)
path, result = [], []
self.dfs(nums, 0, path, result)
return result def dfs(self, nums, index, path, result):
result.append(list(path)) for i in range(index, len(nums)):
if i > 0 and nums[i] == nums[i-1] and i > index:
continue path.append(nums[i])
self.dfs(nums, i+1, path, result)
path.pop()
dfs 排列组合——找所有子集(重复元素和不重复元素)的更多相关文章
- Codeforces 991E. Bus Number (DFS+排列组合)
解题思路 将每个数字出现的次数存在一个数组num[]中(与顺序无关). 将出现过的数字i从1到num[i]遍历.(i from 0 to 9) 得到要使用的数字次数数组a[]. 对于每一种a使用排列组 ...
- DFS排列组合问题
这四个使用DFS来求解所有组合和排列的例子很有代表性,这里做一个总结: 1.不带重复元素的子集问题 public ArrayList<ArrayList<Integer>> s ...
- [leetcode] 题型整理之排列组合
一般用dfs来做 最简单的一种: 17. Letter Combinations of a Phone Number Given a digit string, return all possible ...
- 排列 && 组合
最近编程经常遇到需要 排列&&组合(求子集) 的问题:遂整理一下. 1. 数字的排列与组合(递归):O(n!),O(nC(n,k)) * O(n) #include <stdio ...
- DFS实现排列组合
所谓排列,是指从给定的元素序列中依次取出元素,需要考虑取出顺序.比如,取出元素3, 5,因取出顺序的不同,则形成的序列{3, 5}与{5, 3}是不同的排列序列.对于长度为n的元素序列取出k个元素,则 ...
- 面试题: 已知一个含有n个不同元素的集合,要求打印其所有具有k个元素的子集(不允许有重复的)
TX面试题2: 已知一个含有n个元素的集合,要求打印其所有具有k个元素的子集(不允许有重复的) 题目分析, 为了便于说明,不妨将问题简化一下: 已知一个盒子中有n个不同的球,分别标记为{a1,a2,. ...
- dfs 全排列 使用交换——含重复元素和非重复元素
15. 全排列 中文 English 给定一个数字列表,返回其所有可能的排列. 样例 样例 1: 输入:[1] 输出: [ [1] ] 样例 2: 输入:[1,2,3] 输出: [ [1,2,3], ...
- PHP的排列组合问题 分别从每一个集合中取出一个元素进行组合,问有多少种组合?
首先说明这是一个数学的排列组合问题C(m,n) = m!/(n!*(m-n)!) 比如:有集合('粉色','红色','蓝色','黑色'),('38码','39码','40码'),('大号','中号') ...
- N个数组中所有元素的排列组合(笛卡尔积)算法
(1)N个数组对象中所有元素排列组合算法 private List<List<Object>> combineAlg(List<Object[]> nArray) ...
随机推荐
- 2018-2019-2 20165315《网络对抗技术》Exp7 网络欺诈防范
2018-2019-2 20165315<网络对抗技术>Exp7 网络欺诈防范 一.实验内容 本实践的目标理解常用网络欺诈背后的原理,以提高防范意识,并提出具体防范方法.具体实践有 简单应 ...
- 简单说说JavaScript的Generator 实现(ES6)
Generator 是 ES6 中新增的语法,和 Promise 一样,都可以用来异步编程 // 使用 * 表示这是一个 Generator 函数 // 内部可以通过 yield 暂停代码 // 通过 ...
- 【Gamma】Scrum Meeting 7
前言 会议定点:大运村公寓 会议时间:2019/6/5 会议目的:明确下阶段目标 一.任务进度 组员 上周任务进度 下阶段任务 大娃 修复后端bug 辅助做好引导录屏 二娃 撰写会议博客 撰写会议博客 ...
- MVC发布出现:未能将文件bin\xxx.xml 复制到 obj\Release\PackageTmp\bin\xxx.xml,未能找到文件
之前写的项目好好的,也可以发布,然后今天要发布MVC项目,一直报错,报下面这个错误 莫名其妙搞了好久,没搜到合理的解决方案,结果就只能瞎搞了. 突然想起了,我前几天犯贱把项目根目录下的bin文件夹和o ...
- 批处理中setlocal enabledelayedexpansion的作用详细整理
转自:https://www.jb51.net/article/29323.htm 设置本地为延迟扩展.其实也就是:延迟变量,全称延迟环境变量扩展, 想进阶,变量延迟是必过的一关!所以这一部分希望你能 ...
- 接口性能指标TP90
TP90,即,Top percentile 90, 前90%的意思. 这是一个常用于网站性能监控的指标.tp90是一个时间值,例如tp90=3ms,其含义是90%的请求,在3ms之内,可以得到响应. ...
- Tensorflow2 快速简单安装命令
使用如下命令 pip3 install numpy pandas matplotlib sklearn tensorflow==2.0.0-alpha0 -i https://pypi.doubani ...
- Effective.Java第45-55条(规范相关)
45. 明智谨慎地使用Stream 46. 优先考虑流中无副作用的函数 47. 优先使用Collection而不是Stream作为方法的返回类型 48. 谨慎使用流并行 49. 检查参数有效 ...
- Java 并发-Unsafe 相关整理
https://www.jianshu.com/p/2e5b92d0962e 1. Unsafe 类 Java 不能直接访问操作系统底层,而是通过本地方法来访问.Unsafe 类提供了硬件级别的原子操 ...
- C/C++ 的编译和链接
C/C++文件 C/C++程序文件包括 .h .c .hpp .cpp,其中源文件(.c .cpp)是基本的编译单元,头文件(.h .hpp)不会被编译器编译. C/C++项目构建(build)过程, ...