Medium
Given an integer array nums
of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Constraints:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
nums
are unique.To solve the “Subsets” problem in Swift with the Solution class, follow these steps:
subsets
in the Solution
class that takes an integer array nums
as input and returns all possible subsets of nums
.generateSubsets
that takes the current subset, the current index in the array, and the array nums
as parameters.nums
, add the current subset to the result list.generateSubsets
with the next index.generateSubsets
with the next index.generateSubsets
function with an empty subset and the starting index 0.Here’s the implementation of the subsets
method in Swift:
class Solution {
func subsets(_ nums: [Int]) -> [[Int]] {
var res = \[\[Int]]()
solve(nums, &res, [Int](), 0)
return res
}
private func solve(_ nums: [Int], _ res: inout [[Int]], _ temp: [Int], _ start: Int) {
res.append(temp)
for i in start..<nums.count {
var newTemp = temp
newTemp.append(nums[i])
solve(nums, &res, newTemp, i + 1)
}
}
}
This implementation uses backtracking to generate all possible subsets of the input array nums
. It has a time complexity of O(2^N), where N is the number of elements in the input array.