(*)剑指offer 面试题43:n个骰子的点数

题目:
把n个骰子仍在地上,所有骰子朝上一面的点数之和为s。输入n,打印出s的所有可能的值出现的概率。

n个骰子的点数之和最小为n,最大值为6n,n个骰子的所有点数的排列数为6^n,需要先统计出每一个点数出现的次数。

解法:
定义一个长度为6n-n+1的数组,和为s的点数出现的次数保存到数组第s-n个元素里。

int g_maxValue = 6;
void printProbability(int number) {
    if (number < 1)  return;
    int maxSum = number*g_maxValue;
    int  *pProbability = new int[maxSum - number + 1];
    for (int i = number; i <= maxSum; ++i) {
        pProbability[i - number] = 0;
    }
    probability(number, pProbability);
    int total = pow(g_maxValue, number);
    for (int i = number; i <= maxSum; ++i) {
        double ratio = (double)pProbablity[i-number]/total;
        cout << ratio;
    }
    delete[] pProbability;
}

void probability(int number, int* pProbability) {
    for (int i = 1; i <= g_maxValue; ++i) {
        probabilityCore(number, number, i, 0, pProbability);
    }   
}

void probabilityCore(int original, int current, int value, int tmpSum, int* pProbability) {
    if (current == 1) {
        int sum = value + tmpSum;
        ++pProbability[sum - original];
    } else {
        for (int i = 1; i <= g_maxValue; ++i) {
            int sum = value + tmpSum;
            probabilityCore(original, current-1, i, sum, pProbability);
        }
    }
}

解法二:

void printProbability(int number) {
    if (number < 1)  return;
    int* pProbabilities[2];
    pProbabilities[0] = new int[g_maxValue * number + 1];
    pProbabilities[1] = new int[g_maxValue * number + 1];
    for (int i = 0; i < g_maxValue * number + 1; ++i) {
        pProbabilities[0][i] = 0;
        pProbabilities[1][i] = 0;
    }
    
    int flag = 0;
    for (int i = 1; i <= g_maxValue; ++i) {
        pProbabilities[flag][i] = 1;
    }
    for (int k = 2; k <= number; ++k) {
        for (int i = 0; i < k; ++i) {
            pProbabilities[1-flag][i] = 0;
        }
        for (int i = 1*k; i <= g_maxValue*k; ++i) {
            pProbabilities[1-flag][i] = 0;
            for (int j = 1; j <= i && j <= g_maxValue; ++j) {
                pProbabilities[1-flag][i] += pProbabilities[flag][i-j];
            }
        }
        flag = 1 - flag;
    }
    double total = pow((double)g_maxValue, number);
    for (int i = number; i <= g_maxValue * number; ++i) {
        double ratio = (double)pProbabilities[flag][i]/total;
        cout << ratio;
    }
    delete[] pProbabilities[0];
    delete[] pProbabilities[1];
}

推荐阅读更多精彩内容