题目链接:https://leetcode.cn/problems/subsets-ii/submissions/591733085/
题意:
给你一个数组,输出不同数字的组合(若两个组合都挑一个1,一个2,无论顺序如何,只输出一个)
思路:
先排序,将不同数字分组,再讨论每组选0,1,2,...n个的情况
class Solution {
public:vector<vector<int>> subsetsWithDup(vector<int>& nums) {vector<vector<int>>ans;sort(nums.begin(),nums.end());vector<int>path;dfs(ans,path,nums,0);return ans;}void dfs(vector<vector<int>>&ans,vector<int>path,vector<int>nums,int i){if(i==nums.size()){ans.push_back(path);return;} auto temp=upper_bound(nums.begin(),nums.end(),nums[i]);int k= temp==nums.end()? nums.size():temp-nums.begin();dfs(ans,path,nums,k);for(;i<k;i++){path.push_back(nums[i]);dfs(ans,path,nums,k);} }
};