算法學習--子集生成

//子集生成
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <list>
#include <set>
using namespace std;

//快速冪運算
/*巧算 m=1010(利用二進制)*/
int myPow_4(int n, int m)
{
	int pingfangshu = n;
	int result = 1;
	while (m != 0) {
		//遇到1累乘現在的冪
		if ((m & 1) == 1)
			result *= pingfangshu;
		//每移位一次,冪累乘方一次
		pingfangshu = pingfangshu * pingfangshu;
		//右移一位
		m >>= 1;
	}
	return result;
}

//逐步生成(迭代)
set<set<int>> getSubset_1(int arr[], int n) {
	set<set<int>> res;
	set<int> kong;
	res.insert(kong);//初始化爲空集
	//遍歷每一個元素
	for (int i = 0; i < n; i++) {
		set<set<int>> new_res;//新建一個大集合(臨時)
		new_res = res;//把原來集合中的每一個子集都加入到新集合中(這個其實就是不加入當前元素的情況)
		//遍歷之前的集合,對於當前的元素,可以選擇加或者不加
		for (set<int> s : res) {
			set<int> temp = s;
			temp.insert(arr[i]);//把當前元素加進去
			new_res.insert(temp);
		}
		res = new_res;//更新大集合
	}
	return res;
}

//遞歸解法
//cur表示當前元素的下標
set<set<int>> getSubset_2(int arr[], int cur) {
	set<set<int>> newSet;
	if (cur == 0) {
		set<int> empty_set;//空集
		set<int> first;//只包含第一個元素的集合
		first.insert(arr[cur]);
		newSet.insert(empty_set);
		newSet.insert(first);
		return newSet;
	}
	set<set<int>> oldSet = getSubset_2(arr, cur - 1);
	//遍歷舊集合的每一個元素(子集),對於當前的元素(數組裏的元素),可以選擇加或者不加
	for (set<int> s : oldSet) {
		newSet.insert(s);//不加的情況
		set<int> temp = s;
		temp.insert(arr[cur]);
		newSet.insert(temp);//加上當前元素的情況
	}
	return newSet;
}

//二進制解法(可以按字典序逆序)
list<list<int>> getSubset_3(int arr[], int n) {
	sort(arr, arr + n);//數組從小到大排序
	list<list<int>> res;//大集合
	for (int i = myPow_4(2, n) - 1; i > 0; i--){
		list<int> s;//對於每個i建立一個集合
		for (int j = n - 1; j >= 0 ; j--){//檢查哪個位上的二進制爲1
			if (((i >> j) & 1) == 1) {
				s.push_back(arr[j]);
			}
		}
		res.push_back(s);
	}
	return res;
}


int main() {
	int arr[5] = { 1,2,3,4,5 };
	set<set<int>> s = getSubset_2(arr, 4);
	//如果只要求非空子集,就把大集合中的空集刪除即可
	//set<int> empty_set;//新建一個空集便於刪除結果集合中的空集------刪除方法1
	//set<set<int>>::iterator it = s.begin();//指向第一個元素(即空集)的迭代器-------刪除方法2
	//s.erase(empty_set);
	//打印所有的子集
	for (set<int> ss : s) {
		cout << "[ ";
		for (int n : ss) {
			cout << n << " ";
		}
		cout << "]" << endl;
	}


	//二進制解法
	int arr_2[3] = { 1,2,3 };
	list<list<int>> l = getSubset_3(arr_2, 3);
	for (list<int> lis : l) {
		cout << "[ ";
		for (int n : lis) {
			cout << n << " ";
		}
		cout << "]" << endl;
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章