-
Notifications
You must be signed in to change notification settings - Fork 215
/
Copy pathMedium_078_Subsets.swift
50 lines (40 loc) · 988 Bytes
/
Medium_078_Subsets.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
https://leetcode.com/problems/subsets/
#78 Subsets
Level: medium
Given a set of distinct integers, 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,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Inspired by @thumike at https://leetcode.com/discuss/9213/my-solution-using-bit-manipulation
*/
import Foundation
struct Medium_078_Subsets {
static func subsets(_ n: [Int]) -> [[Int]] {
var nums = n
nums.sort {$0 < $1}
let elemNum = nums.count
let subsetNum = Int(pow(2.0, Double(elemNum)))
var subsets: [[Int]] = [[Int]](repeating: [], count: subsetNum)
for i in 0..<elemNum {
for j in 0..<subsetNum {
if ((j >> i) & 1) != 0 {
subsets[j].append(nums[i])
}
}
}
return subsets
}
}