N个骰子的点数

题目:把n个骰子仍在地上,所有点数

#include 

using namespace std;

const int g_maxValue = 6;
const int number = 6;

int array[(number - 1) * g_maxValue + 1];

void probility(int original, int current, int sum, int *array)
{
	if (current == 0)
	{
		array[sum - original]++;
		return;
	}

	for (int i = 1; i <= g_maxValue; i++)
	{
		probility(original, current - 1, sum + i, array);
	}
}

void generateValue(int *array, int size)
{
	if (array == NULL || size <= 0)
		return;

	for (int i = number; i <= number * g_maxValue; i++)
	{
		array[i - number] = 0;
	}

	probility(number, number, 0, array);

	for (int i = 0; i < (number - 1) * g_maxValue + 1; i++)
	{
		cout << array[i] << " ";
	}
}

void main()
{
	generateValue(array, (number - 1) * g_maxValue + 1);
}

循环解法,和书上本质一样,但是略有不同

#include 

using namespace std;

void PrintProbability(int number)
{
	const int g_maxValue = 6;

	int *array[2];
	for (int i = 0; i < 2; i++)
	{
		array[i] = new int[g_maxValue * number];
	}

	for (int i = 0; i < g_maxValue * number; i++)
	{
		array[0][i] = 0;
		array[1][i] = 0;
	}
	
	int flag = 0;
	for (int i = 0; i < g_maxValue; i++)
	{
		array[flag][i] = 1;
	}

	for (int i = 1; i < number; i++)
	{
		for (int j = 0; j < i; j++)
			array[1 - flag][j] = 0;
		for (int j = i;  j < (i + 1) * g_maxValue; j++)
		{
			array[1 - flag][j] = 0;
			for (int k = 1; k <= j && k <= g_maxValue; k++)
				array[1 - flag][j] += array[flag][j - k];
		}

		flag = 1 - flag;
	}

	for (int i = number - 1; i < g_maxValue * number; i++)
	{
		cout << array[flag][i] << " ";
	}
}

void main()
{
	PrintProbability(2);
}


你可能感兴趣的:(算法)