Subsets leetcode
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]]
import java.util.*;
public class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
backtrack(nums, 0, temp, result);
return result;
}
private void backtrack(int[] nums, int start, List<Integer> temp, List<List<Integer>> result) {
result.add(new ArrayList<>(temp)); // 💥 Add current subset
for (int i = start; i < nums.length; i++) {
temp.add(nums[i]); // Choose
backtrack(nums, i + 1, temp, result); // Explore
temp.remove(temp.size() - 1); // Unchoose
}
}
}
Comments
Post a Comment