Subsets Leetcode Solution

In this post, we are going to solve the Subsets Leetcode Solution problem of Leetcode. This Leetcode problem is done in many programming languages like C++, Java, and Python.

Subsets Leetcode Solution
Subsets Leetcode Solution


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]]


  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • All the numbers of nums are unique.

Now, lets see the leetcode solution of Subsets Leetcode Solution.

Subsets Leetcode Solution in Python

class Solution:
  def subsets(self, nums: List[int]) -> List[List[int]]:
    ans = []

    def dfs(s: int, path: List[int]) -> None:

      for i in range(s, len(nums)):
        dfs(i + 1, path + [nums[i]])

    dfs(0, [])
    return ans

Subsets Leetcode Solution in CPP

class Solution {
  vector<vector<int>> subsets(vector<int>& nums) {
    vector<vector<int>> ans;
    dfs(nums, 0, {}, ans);
    return ans;

  void dfs(const vector<int>& nums, int s, vector<int>&& path,
           vector<vector<int>>& ans) {

    for (int i = s; i < nums.size(); ++i) {
      dfs(nums, i + 1, move(path), ans);

Subsets Leetcode Solution in Java

class Solution {
  public List<List<Integer>> subsets(int[] nums) {
    List<List<Integer>> ans = new ArrayList<>();
    dfs(nums, 0, new ArrayList<>(), ans);
    return ans;

  private void dfs(int[] nums, int s, List<Integer> path, List<List<Integer>> ans) {
    ans.add(new ArrayList<>(path));

    for (int i = s; i < nums.length; ++i) {
      dfs(nums, i + 1, path, ans);
      path.remove(path.size() - 1);

Note: This problem Subsets is generated by Leetcode but the solution is provided by Chase2learn This tutorial is only for Educational and Learning purposes.

NEXT: Word Search Leetcode Solution

Sharing Is Caring

Leave a Comment