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

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
posted @ 2012-08-07 21:39  苦逼程序猴  阅读(296)  评论(0编辑  收藏  举报