题目

子集

给定一个含不同整数的集合,返回其所有的子集

样例

如果 S = [1,2,3],有如下的解:

  1. [
  2. [3],
  3. [1],
  4. [2],
  5. [1,2,3],
  6. [1,3],
  7. [2,3],
  8. [1,2],
  9. []
  10. ]
注意

子集中的元素排列必须是非降序的,解集必须不包含重复的子集

挑战

你可以同时用递归与非递归的方式解决么?

解题

根据上面求排列的思想很类似,还是深度优先遍历。由于输出每个子集需要升序,所以要先对数组进行排序。求出所以的子集,也就是求出所以的组合方式 + 空集

问题转化为求组合方式的问题

参考链接不仅要考虑起始位置,还需要考虑长度,这样才是组合 C(n,k),由于我只想到要考虑起始位置,而长度问题在程序中增加,一直没有解决问题

核心程序

  1. public void helper(int[] nums,int start,int len,
  2. ArrayList<Integer> list,ArrayList<ArrayList<Integer>> res){
  3. if( list.size() == len){
  4. res.add(new ArrayList<Integer>(list));
  5. return;
  6. }
  7. for(int i=start;i< nums.length;i++){
  8. if(list.contains(nums[i])){
  9. continue;
  10. }
  11. list.add(nums[i]);
  12. helper(nums,i+1,len,list,res);
  13. list.remove(list.size()-1);
  14. }
  15.  
  16. }
  1. class Solution {
  2. /**
  3. * @param S: A set of numbers.
  4. * @return: A list of lists. All valid subsets.
  5. */
  6. public ArrayList<ArrayList<Integer>> subsets(int[] nums) {
  7. // write your code here
  8. ArrayList<Integer> list = new ArrayList<Integer>();
  9. ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
  10. if(nums == null || nums.length ==0)
  11. return res;
  12. Arrays.sort(nums);
  13.  
  14. res.add(list);
  15. for(int len = 1;len<= nums.length;len++){
  16. helper(nums,0,len,list,res);
  17.  
  18. }
  19. return res;
  20. }
  21. public void helper(int[] nums,int start,int len,
  22. ArrayList<Integer> list,ArrayList<ArrayList<Integer>> res){
  23. if( list.size() == len){
  24. res.add(new ArrayList<Integer>(list));
  25. return;
  26. }
  27. for(int i=start;i< nums.length;i++){
  28. if(list.contains(nums[i])){
  29. continue;
  30. }
  31. list.add(nums[i]);
  32. helper(nums,i+1,len,list,res);
  33. list.remove(list.size()-1);
  34. }
  35.  
  36. }
  37. }

Java Code

九章中程序进行了优化,长度不考虑,递归一次list的值都是子集的一个元素

  1. class Solution {
  2. /**
  3. * @param S: A set of numbers.
  4. * @return: A list of lists. All valid subsets.
  5. */
  6. public ArrayList<ArrayList<Integer>> subsets(int[] nums) {
  7. // write your code here
  8. ArrayList<Integer> list = new ArrayList<Integer>();
  9. ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
  10. if(nums == null || nums.length ==0)
  11. return res;
  12. Arrays.sort(nums);
  13. helper(nums,0,list,res);
  14.  
  15. return res;
  16. }
  17. public void helper(int[] nums,int start, ArrayList<Integer> list,ArrayList<ArrayList<Integer>> res){
  18. res.add(new ArrayList<Integer>(list));
  19. for(int i=start;i< nums.length;i++){
  20. if(list.contains(nums[i])){
  21. continue;
  22. }
  23. list.add(nums[i]);
  24. helper(nums,i+1,list,res);
  25. list.remove(list.size()-1);
  26. }
  27.  
  28. }
  29. }

Java Code

  1. class Solution:
  2. """
  3. @param S: The set of numbers.
  4. @return: A list of lists. See example.
  5. """
  6. def subsets(self, S):
  7. def dfs(depth, start, valuelist):
  8. res.append(valuelist)
  9. if depth == len(S): return
  10. for i in range(start, len(S)):
  11. dfs(depth+1, i+1, valuelist+[S[i]])
  12. S.sort()
  13. res = []
  14. dfs(0, 0, [])
  15. return res

Python Code

根据位运算进行求解

  1. // 1 << n is 2^n
  2. // each subset equals to an binary integer between 0 .. 2^n - 1
  3. // 0 -> 000 -> []
  4. // 1 -> 001 -> [1]
  5. // 2 -> 010 -> [2]
  6. // ..
  7. // 7 -> 111 -> [1,2,3]

下面是我自己实现

  1. class Solution {
  2. /**
  3. * @param S: A set of numbers.
  4. * @return: A list of lists. All valid subsets.
  5. */
  6. public ArrayList<ArrayList<Integer>> subsets(int[] nums) {
  7. // write your code here
  8. int len = nums.length;
  9. ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
  10. if(nums == null || len==0)
  11. return res;
  12. Arrays.sort(nums);
  13. // 1 << n is 2^n
  14. // each subset equals to an binary integer between 0 .. 2^n - 1
  15. // 0 -> 000 -> []
  16. // 1 -> 001 -> [1]
  17. // 2 -> 010 -> [2]
  18. // ..
  19. // 7 -> 111 -> [1,2,3]
  20. for(int i=0;i< 1<<len ;i++){
  21. ArrayList<Integer> list = new ArrayList<Integer>();
  22. // 检测哪一位是 1
  23. int n = i;
  24. for(int j=0;j< len;j++){
  25. if(n%2==1)
  26. list.add(nums[j]);
  27. n=n/2;
  28. }
  29. res.add(list);
  30. }
  31. return res;
  32. }
  33. }

九章中判断第几位是1的程序如下:

  1. for (int i = 0; i < (1 << n); i++) {
  2. ArrayList<Integer> subset = new ArrayList<Integer>();
  3. for (int j = 0; j < n; j++) {
  4. // check whether the jth digit in i's binary representation is 1
  5. if ((i & (1 << j)) != 0) {
  6. subset.add(nums[j]);
  7. }
  8. }
  9. result.add(subset);
  10. }

是懂非懂,好像这样也可以判断第几位是1

  1. class Solution:
  2. """
  3. @param S: The set of numbers.
  4. @return: A list of lists. See example.
  5. """
  6. def subsets(self, nums):
  7. # write your code here
  8. res = []
  9. size = len(nums)
  10. nums.sort()
  11. if nums == None or size == 0:
  12. return res
  13. for i in range(1<<size):
  14. lst=[]
  15. n = i
  16. for j in range(size):
  17. if n%2==1:
  18. lst.append(nums[j])
  19. n/=2
  20. res.append(lst)
  21. return res

Python Code

lintcode 中等题:subSets 子集的更多相关文章

  1. lintcode 中等题:subsets II 带重复元素的子集

    题目 带重复元素的子集 给定一个可能具有重复数字的列表,返回其所有可能的子集 样例 如果 S = [1,2,2],一个可能的答案为: [ [2], [1], [1,2,2], [2,2], [1,2] ...

  2. lintcode 中等题:partition array 数组划分

    题目 数组划分 给出一个整数数组nums和一个整数k.划分数组(即移动数组nums中的元素),使得: 所有小于k的元素移到左边 所有大于等于k的元素移到右边 返回数组划分的位置,即数组中第一个位置i, ...

  3. lintcode 中等题:permutations II 重复数据的全排列

    题目 带重复元素的排列 给出一个具有重复数字的列表,找出列表所有不同的排列. 样例 给出列表 [1,2,2],不同的排列有: [ [1,2,2], [2,1,2], [2,2,1] ] 挑战 使用递归 ...

  4. lintcode 中等题:permutations 全排列

    题目 全排列 给定一个数字列表,返回其所有可能的排列. 您在真实的面试中是否遇到过这个题? Yes 样例 给出一个列表[1,2,3],其全排列为: [ [1,2,3], [1,3,2], [2,1,3 ...

  5. lintcode 中等题: Implement Trie

    题目 Implement Trie Implement a trie with insert, search, and startsWith methods. 样例   注意 You may assu ...

  6. lintcode 中等题:majority number III主元素III

    题目 主元素 III 给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的1/k. 样例 ,返回 3 注意 数组中只有唯一的主元素 挑战 要求时间复杂度为O(n),空间复杂度为O( ...

  7. lintcode 中等题:N Queens II N皇后问题 II

    题目: N皇后问题 II 根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局. 样例 比如n=4,存在2种解决方案 解题: 和上一题差不多,这里只是求数量,这个题目定义全局变量,递 ...

  8. lintcode 中等题:A + B Problem A + B 问题

    题目: 中等 A + B 问题 给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符. 如果 a=1 并且 b=2,返回3 注意 你不需要从输入流读入数据,只需要根据aplusb的两个参数 ...

  9. lintcode 中等题:搜索旋转排序数组II

    题目 搜索旋转排序数组 II 跟进“搜索旋转排序数组”,假如有重复元素又将如何? 是否会影响运行时间复杂度? 如何影响? 为何会影响? 写出一个函数判断给定的目标值是否出现在数组中. 样例 给出[3, ...

随机推荐

  1. 解决ubuntu 14.04 下eclipse 3.7.2 不能启动,报Could not detect registered XULRunner to use 或 org.eclipse.swt.SWTError: XPCOM 等问题的处理

    对于eclipse 3.7.2在ubuntu 14.04下不能启动,需要在 eclipse/configuration 目录下的config.ini文件内增加一行org.eclipse.swt.bro ...

  2. 老式浏览器兼容HTML5和CSS3的问题

      1.让老式浏览器支持HTML5   HTML5能为我们做的事儿很多,最为可口的就是语义化标签的应用,如果你已经在Chrome或者其他支持HTML5的浏览器上用过它的牛x,那这篇文章对你一定有用,因 ...

  3. webpack入门(译)

    本文由官方Tutorial Getting Started整理翻译,因为该指南解决了我在上手webpack过程中遇到的诸多问题.所以在这里推荐给各位新手们~ WELCOME 这份指南始终围绕一个简单例 ...

  4. 最新区分兼容IE6/IE7/IE8/IE9/FF的CSS HACK写法和Css if hack条件语法操作说明

    自从安装了IE8.0正式版本!木头 就对基本的几个 CSS HACK的做一下归纳!希望对网页前端布局DIV+CSS的实施者有所帮助! 本文就主要以:IE6+IE7+IE8+IE9+FF为主要研究对象 ...

  5. Spark菜鸟学习营Day6 分布式代码运行调试

    Spark菜鸟学习营Day6 分布式代码运行调试 作为代码调试,一般会分成两个部分 语法调试,也就是确定能够运行 结果调试,也就是确定程序逻辑的正确 其实这个都离不开运行,所以我们说一下如何让开发的S ...

  6. WPF 系统托盘 图标闪烁

    WPF消息通知 系统托盘,图标闪烁 using System.Windows.Forms; using System.Windows.Threading; public partial class W ...

  7. Redis 代理服务Twemproxy

    1.twemproxy explore 当我们有大量 Redis 或 Memcached 的时候,通常只能通过客户端的一些数据分配算法(比如一致性哈希),来实现集群存储的特性.虽然Redis 2.6版 ...

  8. ORA-00845

    系统版本: [root@yoon ~]# more /etc/oracle-releaseOracle Linux Server release 5.7 数据库版本: Oracle Database ...

  9. C#的winform小合集

    C#的winform小合集 博主很懒,又想记录一下自己的所做所为,仅此而已,供自己日后所看.这个是博主自主学习C#所写的一些小程序,有好玩的,也有一些无聊闲得蛋疼所作的. 内容介绍 C#入门窗口输出h ...

  10. phpcms v9 企业黄页加入企业会员提示“请选择企业库类型!”

    很多新进站长选择使用了PHPCMS v9内容管理系统,它强大的功能无疑吸引了很多人,尤其是企业黄页功能更是其中的佼佼者,但是官方发布的版本兼容性比较差,出现会员加入企业会员提示“请选择企业库类型!”, ...