g0001_0100.s0078_subsets.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0078_subsets;
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Bit_Manipulation #Backtracking
// #Algorithm_II_Day_9_Recursion_Backtracking #Udemy_Backtracking/Recursion
// #Big_O_Time_O(2^n)_Space_O(n*2^n) #2023_08_11_Time_1_ms_(70.60%)_Space_41.8_MB_(71.73%)
import java.util.ArrayList;
import java.util.List;
/**
* 78 - Subsets\.
*
* 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`
* * All the numbers of `nums` are **unique**.
**/
@SuppressWarnings("java:S5413")
public class Solution {
public List> subsets(int[] nums) {
List> res = new ArrayList<>();
solve(nums, new ArrayList<>(), res, 0);
return res;
}
private void solve(int[] nums, List temp, List> res, int start) {
res.add(new ArrayList<>(temp));
for (int i = start; i < nums.length; i++) {
temp.add(nums[i]);
solve(nums, temp, res, i + 1);
temp.remove(temp.size() - 1);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy