求解幂集问题之创建

直接穷举法

//将二进制数加一
/*
  000  {}

  100  {1}
  010  {2}
  110  {1 2}

  001  {3}
  101  {1 3}
  011  {2 3}
  111  {1 2 3}
*/
void inc(int b[], int n) {
	for (int i = 0; i < n; i++) {
		if (b[i])
			b[i] = 0;
		else {
			b[i] = 1;
			break;
		}
	}
 }

void power_set(int a[], int b[], int n) {
	int i, k;
	int pw = pow(2, n);
	cout << "1—" << n << "的幂集" << endl;
	for (i = 0; i < pw; i++) {      //执行2的n次方次
		cout << "{";
		for (k = 0; k < n; k++)
			if (b[k])
				cout << a[k];
		cout << "}";
		inc(b, n);
	}

}

增量穷举法

/*
  {}

  {}
  {1}

  {}
  {1}
  {2}
  {12}

  {}
  {1}
  {2}
  {12}
  {3}
  {13}
  {23}
  {123}

  ···
*/
vector>ps;
void power_set(int n) {
	vector>ps1;     
	vector>::iterator it;    //幂集迭代器,用来遍历幂集
	vectors;     //为空的向量集,用来初始化空集
	ps.push_back(s);  
	for (int i = 1; i <= n; i++) {
		ps1 = ps;         //ps1用来存放前一次操作得到的幂集
		for (it = ps1.begin(); it != ps1.end(); ++it) {
			(*it).push_back(i);
			ps.push_back(*it);
		}
	}
}

你可能感兴趣的:(求解幂集问题之创建)