心胸决定格局,眼界决定境界...

某个集合的子集问题

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;
}

 

posted @ 2014-08-27 10:09  WELEN  阅读(276)  评论(0编辑  收藏  举报