[Backtracking] [leetcode] Output all possible subsets of the array (with duplicate elements)

topic:

Given an integer array nums that may contain repeated elements, return all possible subsets (power sets) of the array.

Note: The solution set cannot contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

source:

90. Subset II

Problem-solving ideas: backtracking

Refer to  all possible subsets of the output array and  add a line of deduplication code above the code: while (i+1<nums.size() && nums[i+1] == nums[i]) i++;

Here is an explanation of the combination process . If 3 numbers are selected from 5 numbers, after selecting a number, the number selected later should be after the current number. If you choose 2, the number after it can only be 3, 4, 5, as shown in the figure below.

In the case of selecting 2 and 3, after selecting 4 to output, the selected 4 should be deleted and replaced with 5. Select a number, process it recursively, and delete the number. This process is backtracking .

If the numbers are repeated, the numbers are sorted first. If there is a sequence of 1, 2, 2, 3, 3, 4, 5, the tree structure composed of the second number 2 will be part of the first tree structure, so Just skip the same number in the loop.

code show as below:

class Solution {
public:
    vector< vector<int> > result;
    vector<int> path;
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        for (int i = 0; i <= nums.size(); i++) {
            back(nums, 0, i);
        }
        return result;
    }
    void back(const vector<int>& nums, int start, int k) {
        if (path.size() == k) {
            result.push_back(path);
            return;
        }
        for (int i = start; i < nums.size(); i++) {
            if (path.size() + nums.size() - i + 1 < k) break;
            path.push_back(nums[i]);
            back(nums, i+1, k);
            path.pop_back();
            while (i+1<nums.size() && nums[i+1] == nums[i]) i++; // 增加这一行,去重
        }
    }
};

 

Guess you like

Origin blog.csdn.net/hbuxiaoshe/article/details/115013103