程序员面试题精选100题(43)-n个骰子的点数[算法]

来源:互联网 发布:魅力女生知乎 编辑:程序博客网 时间:2024/05/22 12:06
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace HellWorld{    class Program    {        public static void PrintSumProbabilityOfDices(int num)        {            int max = num*6;            int[,] arr = new int[num + 1,max + 1];            for (int i = 1; i <= 6;i++ )            {                arr[1, i] = 1;            }            for (int k = 2; k <= num;k++ )            {                for (int i = k; i <=6 * k;i++ )                {                    for (int j = 1; j <= 6;j++ )                    {                        if(i>=j)                            arr[k, i] += arr[k-1,i - j];                    }                }            }            double total = Math.Pow((double)6, num);            for (int j = num; j <= max; j++)            {                double ratio = arr[6, j]/total;                Console.WriteLine("{0}:{1}",arr[6,j],ratio );           }        }        static void Main(string[] args)        {            PrintSumProbabilityOfDices(6);            Console.ReadLine();        }    }}状态转移方程k表示骰子个数,n表示k个骰子的点数和                | - F(k-1, n-6) + F(k-1, n-5) + F(k-1, n-4) +   F(k-1, n-3) + F(k-1, n-2) + F(k-1, n-1)  |  对于 k > 0, k <= n <= 6*k F(k, n) = |                 |- 0 对于 n < k or n > 6*k初始化k=1, F(1,1)=F(1,2)=F(1,3)=F(1,4)=F(1,5)=F(1,6)=1

原创粉丝点击