|  | 
 
 发表于 2014-9-13 10:45:50
|
显示全部楼层 
| 本帖最后由 friendan 于 2014-9-14 14:25 编辑 
 效果截图:
 
   
 ------------------------------------------------------------------
 代码:
 
 复制代码// TestCpp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdio.h"
int a[] = {1,2,3,4,5,6,7,8,9,0};        // 定义一个 a[10]
#define N  10   // 10个数
#define M  1    // 取M个数,M是动态的1到10,这里初始化为1
int queue[N] = {0}; // 每产生一种情况,就保存一种情况
int top = 0;
int iIndex = 0;
int b[N][1000] = {0};            // 定义一个b,因为不知道有多少种情况,所有第二列能大就大吧,这里是1000
// 递归遍历所有情况
void comb(int s, int n, int m)
{
    int i;
    if (s > n)
        return ;
    if (top == m)   // 获得一种
    {
        for (i = 0; i < m; i++)
        {
            b[m-1][iIndex++] = queue[i];        // 结果放入b
        }
        return ;
    }
    queue[top++] = a[s];
    comb(s+1, n, m);
    top--;
    comb(s+1, n, m);
}
//组合算法
int GetCount(int n, int m)
{
    // 求n的阶乘
    int iN = 1;
    int i = 0;
    for(i = 1; i<= n ;i++)
    {
        iN = iN*i;
    }
    //求m的阶乘
    int iM = 1;
    for(i = 1; i<= m ;i++)
    {
        iM = iM*i;
    }
    //求n-m的阶乘
    int iNM = 1;
    for(i = 1; i<= (n-m) ;i++)
    {
        iNM = iNM*i;
    }
    // 打印计算结果
    //printf("iN = %2d,iM = %-7d, iNM = %d \n", iN, iM, iNM);
    // 返回计算结果
    return iN / (iM*iNM);
}
void ShowB(int idx, int count)
{
    int lie = 0;
    for(int i = 0; i < count; i++)
    {
        for(int j = 0; j < (idx+1); j++)
         printf("%d", b[idx][lie++]);
        printf("\t");
    }
}
int main(int argc, char* argv[])
{
    int i = 0;
    for(i = 10; i >= 1; i--)    // 获取所有情况
    {
        iIndex = 0;
        comb(0, N, i);
    }
    // 遍历结果
    for(i = 10; i >= 1; i--)
    {
        int count = GetCount(N, i);
        printf("\n取%d个数的%d种可能: \n", i, count);
        ShowB(i-1, GetCount(N, i));
    }
    getchar();  // 暂停程序
    return 0;
}
 
 
 | 
 |