美文网首页
78. 子集-leetcode

78. 子集-leetcode

作者: 佛祖拿屠刀 | 来源:发表于2018-12-24 22:54 被阅读0次

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: nums = [1,2,3]
输出:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

这道题目是有一点陷阱的意思

实际上一个数组长度为n,

那么这个数组的子集就有2的n次方个

所以可以用位运算来解决,

一共是n位,

每一位代表的是一个数组中的对应的一个元素,

然后能得出一个数,

把这些所有的数组合起来 就是答案了

class Solution {
    func subsets(_ nums: [Int]) -> [[Int]] {
        let count = 1 << nums.count
       var res = [[Int]].init()
        for n in 0..<count {
            var index = 0
            var temp = n
            var tempArray = [Int].init()
            while (temp >> index) > 0 {
                if ( temp >> index ) & 0b01 == 1 {
                    tempArray.append(nums[index])
                }
                index = index + 1
            }
            res.append(tempArray)            
        }
        return res
    }
}

相关文章

  • LeetCode-78-子集

    LeetCode-78-子集 78. 子集[https://leetcode-cn.com/problems/su...

  • 回溯递归算法

    回溯大法严重依赖【递归】 1、求子集 78. 子集[https://leetcode-cn.com/problem...

  • 子集 + 子集 II AND 零花钱兑换 + 零钱兑换 II

    78. 子集[https://leetcode-cn.com/problems/subsets/] 方法一 枚举 ...

  • Leetcode 78 子集

    78. 子集[https://leetcode-cn.com/problems/subsets/] 题意:给你一个...

  • 78. 子集、90. 子集 II

    78. 子集[https://leetcode-cn.com/problems/subsets/] 给你一个整数数...

  • 4.数组(四)

    https://leetcode-cn.com/tag/array/ 题目汇总75. 颜色分类中等78. 子集中等...

  • 回溯算法团灭子集、排列、组合问题

    读完本文,你可以去力扣拿下如下题目: 78.子集[https://leetcode-cn.com/problems...

  • [LeetCode]78. 子集

    78. 子集给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。说明:解集不能包含重复的子...

  • 78. 子集-leetcode

    给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 说明:解集不能包含重复的子集。 示例...

  • LeetCode:78. 子集

    问题描述 给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。解集 不能 包...

网友评论

      本文标题:78. 子集-leetcode

      本文链接:https://www.haomeiwen.com/subject/ytgtlqtx.html