首页 > 代码库 > 某个集合的子集问题

某个集合的子集问题

int WToSigArray(int* A, int n)//消除重复元素
{
	int i,j,k;
	for( i = k = 1; i < n; i++)
	{
		for( j = 0; j < k; j++)
		{
			if(A[j] == A[i])
			{
			  break;
			}
		}

		if(j == k) 
		{
		    A[k] = A[i];
		    k++;			
		}
	}

	return k;
}

int Subset( int* A, int n, int* B, int m, int cur) //集合A,输出m个元素的子集B
{
	static int number = 0;  

	if(cur == m)
	{   
		number++;
		for(int i = 0; i< m; i++)
		{
			printf("%d ", B[i]);
		}
		printf("\n"); 
	}
	else
	{
		for(int i = 0; i < n; i++)
		{
			int ok = 1; 
			for(int j = 0; j < cur; j++)
			{
				if(B[j] == A[i] || B[j] > A[i])
				{
					ok = 0;
				}

			}

			if(ok)
			{
				B[cur] = A[i];
				Subset(A, n, B, m, cur + 1);
				
			}			

		}
	}

	return number;
}


int WSubset(int* A, int n, int m)
{
	
        int N = WToSigArray(A, n);	
	printf("to single data:\n");
	for(int i = 0; i < N; i++)
	{
		printf("%d ", A[i]);
	}
	printf("\nSubset:\n");
	int   cur = 0;
	int*  B = (int*)malloc(sizeof(int)*m);
	int number = Subset(A, N, B, m, cur);
	delete [] B;
	B = NULL;
	return number;
}

某个集合的子集问题