notes/OJ notes/pages/Leetcode Subsets.md
2022-07-22 16:24:29 +08:00

2 KiB

Leetcode Subsets

2022-07-22 16:16

Algorithms:

#algorithm #backtrack

Data structures:

#DS #vector

Difficulty:

#coding_problem #difficulty-medium

Additional tags:

#leetcode

Revisions:

N/A

tag:#backtrack

Problem

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.

Examples

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.

Thoughts

[!summary] This is a super simple #backtrack problem.

It asked for combinations, so this is a backtrack problem.

go from index 0 to last one, in each iteration, you have two choices:

  • Add this number
  • Don't add this number And we try different combinations at the same level, aka. backtracking.

Pseudo code:

  • When loc == size, append combination to answer
  • Else, start trying different solutions:
    • Append this element to combs and backtrack
    • pop this from combs and backtrack

Solution

class Solution {
  vector<vector<int>> ans;
  vector<int> combs;
  void backtrack(vector<int> &nums, int nextLoc) {
    // We don't require min amount of location

    if (nextLoc == nums.size()) {
      ans.push_back(combs);
    } else {
      combs.push_back(nums[nextLoc]);
      backtrack(nums, nextLoc + 1);

      combs.pop_back();
      backtrack(nums, nextLoc + 1);
    }
  }

public:
  vector<vector<int>> subsets(vector<int> &nums) {
    // Backtracking for accumulating combinations.
    ans = {};
    combs = {};
    backtrack(nums, 0);

    return ans;
  }
};