Problem
Problem page: https://leetcode.com/problems/subsets/
Topics: Array, Backtracking, Bit Manipulation
Difficulty: 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], [] ]
Analysis
A simple search algorithm will do, but each subsequence has to be in ascending order, so I sort the input S right at the start and get that out of the way. I wonder if there's a better algorithm.
Going down and coming back are the two keys to recursive backtracking. On the way down, the branch condition gives me two branches at each step: take the current element or skip it. Once I've considered all the elements, I've reached the termination condition and can return.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-subsets/
