[Backtracking method] ----- find a subset of a set problem

Leetcode 78 original question

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

Example1
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Input: nums = [0]
Output: [[],[0]]

Constraints:

  • 1 <= nums.length <= 10

  • 1 <= nums.length <= 10

  • All the numbers of nums are unique.

Solutions

First of all, this problem is a problem of finding a subset. The problem of finding a subset can be associated with the combination problem and the segmentation problem. If the traversal process of solving the last two problems is formalized as a tree, we can think that the combination problem and the segmentation problem are the problem of seeking The process of the leaf nodes of the whole tree. The subset problem can also be regarded as a combination problem and a segmentation problem, but after obtaining the entire number of leaf nodes, when finding the union of sets, it is necessary to remove the repeated subsets. This process has a high time complexity and can be avoided. .
The elements in nums given in this question are unique . In order to avoid repeated selection of nodes, nodes that have been used before cannot be taken every time when taking nodes. The method of taking nodes as shown in the figure below: follow this method to take
tree
out The nodes in the final set will not be repeated.

Backtracking

The backtracking method is generally divided into three steps:

  1. Determine the parameters and return values ​​of submethods during backtracking
  2. Determine the end condition in the submethod
  3. Determine the logic of entering backtracking in the submethod

Code

#include <vector>
#include <algorithm>

using namespace std;

class leetcode78new {
    
    
public:
    vector<vector<int>> vecRes;
    vector<vector<int>> subsets(vector<int> &nums) {
    
    
        sort(nums.begin(), nums.end());
        vecRes.push_back({
    
    });
        vector<int> vec;
        innerSubsets(nums, 0, vec);
        return vecRes;
    }

    void innerSubsets(vector<int> &nums, int startIndex, vector<int> vec) {
    
    
        if(startIndex == nums.size()) {
    
    
            return;
        }
        for(int i = startIndex; i < nums.size(); ++i) {
    
    
            vec.push_back(nums[i]);
            vecRes.push_back(vec);
            innerSubsets(nums, i+1, vec);
            vec.pop_back();
        }
    }
};

Guess you like

Origin blog.csdn.net/sinat_28199083/article/details/130182702