【剑指Offer】面试题60. n个骰子的点数

题目

把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。输入n,打印出s的所有可能的值出现的概率。
你需要用一个浮点数数组返回答案,其中第 i 个元素代表这 n 个骰子所能掷出的点数集合中第 i 小的那个的概率。

示例 1:

输入: 1
输出: [0.16667,0.16667,0.16667,0.16667,0.16667,0.16667]

示例 2:

输入: 2
输出: [0.02778,0.05556,0.08333,0.11111,0.13889,0.16667,0.13889,0.11111,0.08333,0.05556,0.02778]

限制:1 <= n <= 11

思路

dp[i][j] 表示投完i个骰子后总点数为j的总次数和。投掷第n个骰子的总点数和可以由前n-1一个骰子的转换而来,也就是说如果投掷n-1个骰子的总点数为j-i(1 <= i <= 6),那么第n次投出i即可满足条件:
$dp[n][j] = \sum_{i=1}^6 dp[n-1][j-i]$

代码

时间复杂度:O(n^2)
空间复杂度:O(n^2)

class Solution {
public:
    vector<double> twoSum(int n) {
        vector<vector<double>> dp(n + 1, vector<double>(6 * n + 1, 0));
        vector<double> res;
        for (int i = 1; i <= n; ++i) {
            for (int j = i; j <= 6 * i; ++j) {
                if (i == 1) {
                    dp[i][j] = 1;
                    continue;
                }
                for (int k = 1; k <= 6; ++k) {
                    if (j - k >= i - 1) dp[i][j] += dp[i - 1][j - k];
                }
            }
        }
        for (int i = n; i <= 6 * n; ++i) {
            res.push_back(dp[n][i] * pow(1.0 / 6, n));
        }
        return res;
    }
};

优化空间

在上面方法中,下一行其实只用到了前一行最多6个数,可以优化二维数组为一维数组。
时间复杂度:O(n^2)
空间复杂度:O(n)

class Solution {
public:
    vector<double> twoSum(int n) {
        vector<double> dp(6 * n + 1, 0);
        vector<double> res;
        for (int i = 1; i <= n; ++i) {
            for (int j = i * 6; j >= i; --j) {
                dp[j] = 0;  // 当前数置为0
                if (i == 1) {
                    dp[j] = 1;
                    continue;
                }
                for (int k = 1; k <= 6; ++k) {  // 当前数等于前六个位置累加和
                    if (j - k >= i - 1) dp[j] += dp[j - k];
                }
            }
        }
        for (int i = n; i <= 6 * n; ++i) {
            res.push_back(dp[i] * pow(1.0 / 6, n));
        }
        return res;
    }
};
posted @ 2020-05-09 23:14  Galaxy_hao  阅读(245)  评论(0编辑  收藏  举报