749. Generate All Subsets (Power Set)

MediumRecursionRecursion

Given an integer array nums, return the power set — a list containing every possible subset of nums (including the empty subset and the full array). To guarantee a unique answer, the output must follow this canonical form:
1. Each subset is an ascending-sorted list of its elements.
2. The list of subsets is sorted first by subset length (shortest first), then element-by-element lexicographically.
If nums contains duplicates, duplicate subsets must appear only once (i.e., return the DISTINCT power set).

Input: An integer array nums.

Output: Return a list of lists: [[...],[...],...] following the canonical ordering described above.

Examples

Example 1
Input: [1,2,3]
Output: [[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]
Explanation: All 2^3 = 8 subsets, each sorted internally, list sorted by length then lex.
Example 2
Input: [0]
Output: [[],[0]]
Explanation: Two subsets: the empty set and {0}.
Example 3
Input: [1,1]
Output: [[],[1],[1,1]]
Explanation: Duplicates eliminated: only distinct subsets.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →