力扣 题目90- 子集 II

题目

题解

直接在力扣 题目78- 子集修改 先排序 因为我们不知道后面有没有与前面重复的 所以排序后考虑一种情况 就是重复都在一起

那么我们只要在78题上判断一下重复即可

int loop(vector<int>& nums, vector<vector<int>>& result, vector<int>& alone, int begin) {
    int num = INT_MAX;
    for (int i = begin; i < nums.size(); i++) {
        if (nums[i]!= num) {
            num = nums[i];
            alone.push_back(nums[i]);
            result.push_back(alone);
            loop(nums, result, alone, i + 1);
            alone.pop_back();
        }
    }
    return 0;
}

代码

 1 #include<iostream>
 2 #include<vector>
 3 #include<algorithm>
 4 using namespace std;
 5 int loop(vector<int>& nums, vector<vector<int>>& result, vector<int>& alone, int begin) {
 6     int num = INT_MAX;
 7     for (int i = begin; i < nums.size(); i++) {
 8         if (nums[i]!= num) {
 9             num = nums[i];
10             alone.push_back(nums[i]);
11             result.push_back(alone);
12             loop(nums, result, alone, i + 1);
13             alone.pop_back();
14         }
15     }
16     return 0;
17 }
18 class Solution {
19 public:
20     vector<vector<int>> subsetsWithDup(vector<int>& nums) {
21         sort(nums.begin(), nums.end());
22         vector<vector<int>> result;
23         result.push_back({});
24         vector<int> alone;
25         loop(nums, result, alone, 0);
26         return result;
27     }
28 };
29 
30 int main() {
31     Solution sol;
32     vector<int> nums = { 1,2,3,2 };
33     vector<vector<int>> result = sol.subsetsWithDup(nums);
34     for (int i = 0; i < result.size(); i++) {
35         for (int j = 0; j < result[i].size(); j++) {
36             cout << result[i][j] << " ";
37         }
38         cout << endl;
39     }
40 }
View Code

 

 

posted @ 2022-07-14 14:39  无聊的阿库娅  阅读(11)  评论(0编辑  收藏  举报