Did you know that subset problems are actually template problems?

Did you know that subset problems are actually template problems?

[[426614]]

After understanding the essence, this is a template question

Subset

Link to LeetCode questions: https://leetcode-cn.com/problems/subsets/

Given an integer array nums with no repeated elements, return all possible subsets (power sets) of the array.

Note: The solution set cannot contain repeated subsets.

Example:

Input: nums = [1,2,3]

Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]

Ideas

The subset problem is different from 77. Combination and 131. Splitting palindrome strings.

If we abstract the subset problem, combination problem, and partition problem into a tree, then the combination problem and partition problem are to collect the leaf nodes of the tree, while the subset problem is to find all the nodes of the tree!

In fact, subset is also a combinatorial problem, because its set is unordered, the subset {1,2} and the subset {2,1} are the same.

Since it is unordered, the elements that have been taken will not be taken repeatedly. When writing the backtracking algorithm, for should start from startIndex instead of starting from 0!

Some students asked, when can for start from 0?

When solving permutation problems, we have to start from 0, because sets are ordered. {1, 2} and {2, 1} are two sets. We will talk about permutation problems in subsequent articles.

Taking nums = [1,2,3] in the example, we can abstract the subset into a tree structure as follows:

Subset

From the red line part in the figure, we can see that when traversing the tree, all the nodes are recorded, which is the required subset set.

Back to the trilogy

  • Recursive function parameters

The global variable array path collects elements for the subset, and the two-dimensional array result stores the subset combinations. (It can also be put into the recursive function parameters)

The recursive function parameters are mentioned above, and startIndex is required.

The code is as follows:

  1. vector<vector< int >> result;
  2. vector< int > path;
  3. void backtracking(vector< int >& nums, int startIndex) {

Recursion termination condition

As can be seen from the figure:

Subset

When the remaining set is empty, it is a leaf node.

So when is the remaining set empty?

That is, startIndex is greater than the length of the array, so it terminates because there are no elements to be taken. The code is as follows:

  1. if (startIndex >= nums. size ()) {
  2. return ;
  3. }

In fact, there is no need to add a termination condition, because startIndex >= nums.size(), and the for loop at this level has already ended.

  • Single-layer search logic

To find the subset problem, no pruning is required! Because the subset is to traverse the entire tree.

Then the single-layer recursive logic code is as follows:

  1. for ( int i = startIndex; i < nums. size (); i++) {
  2. path.push_back(nums[i]); // Subset collection elements
  3. backtracking(nums, i + 1); // Note that starting from i+1, elements are not repeated
  4. path.pop_back(); // backtracking
  5. }

C++ Code

According to the backtracking algorithm, you should know this! The backtracking algorithm template given is:

  1. void backtracking(parameters) {
  2. if (termination condition) {
  3. Store the results;
  4. return ;
  5. }
  6.  
  7. for (select: elements in the current layer set (the number of node children in the tree is the size of the set)) {
  8. Processing nodes;
  9. backtracking(path, selection list); // recursion
  10. Backtracking, undoing processing results
  11. }
  12. }

You can write the following backtracking algorithm C++ code:

  1. class Solution {
  2. private:
  3. vector<vector< int >> result;
  4. vector< int > path;
  5. void backtracking(vector< int >& nums, int startIndex) {
  6. result.push_back(path); // Collect subsets and put them above the one where the addition is terminated, otherwise you will miss yourself
  7. if (startIndex >= nums.size ()) { // The termination condition can be omitted
  8. return ;
  9. }
  10. for ( int i = startIndex; i < nums. size (); i++) {
  11. path.push_back(nums[i]);
  12. backtracking(nums, i + 1);
  13. path.pop_back();
  14. }
  15. }
  16. public :
  17. vector<vector< int >> subsets(vector< int >& nums) {
  18. result.clear();
  19. path.clear();
  20. backtracking(nums, 0);
  21. return result;
  22. }
  23. };

In the comments, you can see that you don't need to write the termination condition because we are going to traverse the entire tree.

Some students may worry about whether there will be infinite recursion if the termination condition is not written.

No, because the next layer of each recursion starts from i+1.

This article is reprinted from the WeChat public account "Code Random Thoughts", which can be followed through the following QR code. To reprint this article, please contact the Code Random Thoughts public account.

<<:  Promote 5G integration and innovation and accelerate the digital transformation of the industry

>>:  When the 2G/3G network is down, will your IoT work properly?

Recommend

China Construction Information: Friends of Huawei, with friends Huawei

If there is one common demand among governments a...

The battle between local deployment and cloud-managed WLAN architecture

Enterprises that need to upgrade their traditiona...

Headline: Determine whether it is an IP address

This question has a tricky part. It asks you to d...

Let's talk about NAT protocol???

Hey everyone, this is cxuan. Today we are going t...

Diagram: 5G millimeter wave peak rate calculation

[[390044]] This article is reprinted from the WeC...

FirstByte: Russian KVM monthly payment starts from 55 rubles (≈ RMB 4.78 yuan)

FirstByte is a regular Russian hosting company fo...

Let's talk about network equipment

My home was recently renovated. As a computer pro...

How to achieve end-to-end network slicing?

GPP defines network slicing as one of the main fu...

Operators won’t tell you that you can use the 5G network without a 5G package

According to data disclosed by the Ministry of In...

Wangsu Technology launches edge AI gateway to help developers build AI

On July 11, Wangsu Technology announced the launc...