[LeetCode]Subsets II

本文介绍了一种用于生成包含重复元素集合的所有子集的算法。通过深度优先搜索(DFS)策略,确保子集不重复且元素按非递减顺序排列。采用两种实现方式:一种直接操作元素,另一种使用布尔标志数组来跟踪元素选择。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Solution {
//because Elements in a subset must be in non-descending order.
//so if we sort the vector first.
//If we choose an elem[i] into subset, then we should choose elem[j](i<j<n) into the subset,
//repeat this until there is no element left any more.
//But note: in the same level we can not choose multiple same elements as the new heads of the next subset. 

	void DFS(vector<int>& S, int curPos, vector<int>& oneSubset, vector<vector<int>>& allSubset)
	{
		allSubset.push_back(oneSubset);
		for (int i = curPos; i < S.size(); ++i)
		{
			if(i != curPos && S[i] == S[i-1]) continue;

			oneSubset.push_back(S[i]);
			DFS(S, i+1, oneSubset, allSubset);
			oneSubset.pop_back();
		}
		
	}
public:
	vector<vector<int> > subsetsWithDup(vector<int> &S) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		sort(S.begin(), S.end());
		vector<int> oneSubset;
		vector<vector<int>> allSubset;
		DFS(S, 0, oneSubset, allSubset);
		return allSubset;
	}
};

second time

class Solution {
public:
    void subsetUtil(vector<int>& S, vector<bool>& used, int curIdx, vector<int>& curPath, vector<vector<int> >& allPath)
    {
        if(curIdx == S.size())
        {
            allPath.push_back(curPath);
            return ;
        }
        
        subsetUtil(S, used, curIdx+1, curPath, allPath);
        if(curIdx >= 1 && S[curIdx] == S[curIdx-1] && used[curIdx-1] == false) return;
        used[curIdx] = true;
        curPath.push_back(S[curIdx]);
        subsetUtil(S, used, curIdx+1, curPath, allPath);
        curPath.pop_back();
        used[curIdx] = false;
    }
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        sort(S.begin(), S.end());
        vector<bool> used(S.size(), false);
        vector<vector<int> > allPath;
        vector<int> curPath;
        subsetUtil(S, used, 0, curPath, allPath);
        return allPath;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI记忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值