LintCode : Dices Sum

试题:
Throw n dices, the sum of the dices’ faces is S. Given n, find the all possible value of S along with its probability.

Example
Example 1:

Input: n = 1
Output: [[1, 0.17], [2, 0.17], [3, 0.17], [4, 0.17], [5, 0.17], [6, 0.17]]
Explanation: Throw a dice, the sum of the numbers facing up may be 1, 2, 3, 4, 5, 6, and the probability of each result is 0.17.
Notice
You do not care about the accuracy of the result, we will help you to output results.
代码:

public class Solution {
    /**
     * @param n an integer
     * @return a list of Map.Entry<sum, probability>
     */
    public List<Map.Entry<Integer, Double>> dicesSum(int n) {
        // Write your code here
        // Ps. new AbstractMap.SimpleEntry<Integer, Double>(sum, pro)
        // to create the pair
        long[][] dp = new long[n+1][6*n+1];
        for(int i=1; i<=6; i++){
            dp[1][i] = 1;
        }
        
        for(int i=2; i<=n; i++){
            for(int j=i; j<=6*i; j++){
                for(int k=1; k<=6&&k<=j; k++){
                    dp[i][j] = dp[i][j] + dp[i-1][j-k];
                }
            }
        }
        
        double total = Math.pow(6,n);
        HashMap map = new HashMap<Integer,Double>();
        for(int i=n; i<=6*n; i++){
            map.put(i,dp[n][i]/total);
        }
        
        return new ArrayList<Map.Entry<Integer,Double>>(map.entrySet());
    }
}

猜你喜欢

转载自blog.csdn.net/qq_16234613/article/details/88844890
今日推荐