美文网首页
leetcode 837 New 21 Game

leetcode 837 New 21 Game

作者: Britjeans | 来源:发表于2019-05-28 14:59 被阅读0次

    solution 1 dynamic programming

    This problem is similar to the idea of the classic dynamic programming problem "Climbing Stairs".
    Let dp[i] represents the probability that Alice can accumulate to i points. Think about how we can reach i points from the last state, then we can conclude that dp[i] = dp[i-W] * 1/W + ... + dp[i-1] * 1/W. Now we can implement the algorithm based on the above formula.

        double new21Game(int N, int K, int W) {
            if(K == 0 || N >= K + W) return 1.0;
            vector<double> dp(N + 1, 0);
            dp[0] = 1.0;
            double wSum = 1.0, res = 0.0;
            for(int i = 1; i <= N; i++) {
                dp[i] = wSum / W;
                if(i < K) {
                    wSum += dp[i];
                } else {
                    res += dp[i]; //we will only accumulate the probability for points that are no less than K
                }
                if(i - W >= 0) {
                    wSum -= dp[i-W];
                }
            }
            return res;
        }
    

    相关文章

      网友评论

          本文标题:leetcode 837 New 21 Game

          本文链接:https://www.haomeiwen.com/subject/fntwaqtx.html