Skip to content

Latest commit

 

History

History
52 lines (35 loc) · 859 Bytes

File metadata and controls

52 lines (35 loc) · 859 Bytes

Subsets

Problem Link

https://leetcode.com/problems/subsets/


Pattern

  • Backtracking
  • Recursion

Approach

At each index, choose to include the current element or skip it and continue exploring.


Time Complexity

O(2^n)

Space Complexity

O(n)


Java Solution

import java.util.*;
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        backtrack(nums, 0, new ArrayList<>(), ans);
        return ans;
    }

    private void backtrack(int[] nums, int index, List<Integer> path, List<List<Integer>> ans) {
        ans.add(new ArrayList<>(path));
        for (int i = index; i < nums.length; i++) {
            path.add(nums[i]);
            backtrack(nums, i + 1, path, ans);
            path.remove(path.size() - 1);
        }
    }
}