n个骰子——剑指offer

暴力求解,n个骰子和为s就等于n-1个骰子和分别为s-1~s-6时次数的总和。据此写出代码如下:

int baoli(int n, int s)
{
	if (n < 1)
		return 0;
	if (n == 1)
	{
		if (s < 1 || s > 6)
			return 0;
		else
			return 1;
	}
	int count = 0;
	count = baoli(n - 1, s - 1) + baoli(n - 1, s - 2) + baoli(n - 1, s - 3) + 
            baoli(n - 1, s - 4) + baoli(n - 1, s - 5) + baoli(n - 1, s - 6);
	return count;
}

动态规划,空间复杂度为O(ns),时间复杂度为O(ns);

int times(int n, int s)
{
	vector<vector<int>> f(n + 1, vector<int>(s + 1, 0));
	for (int i = 1; i < 7; i++)
		f[1][i] = 1;
	for(int i = 2; i <= n; i++)
		for(int j = i; j <= s; j++)
			switch (j)
			{
			case 2 :
				f[i][j] = f[i - 1][j - 1];// +f[i - 1][j - 2];
				break;
			case 3:
				f[i][j] = f[i - 1][j - 1] + f[i - 1][j - 2]; // +f[i - 1][j - 3]
				break;
			case 4:
				f[i][j] = f[i - 1][j - 1] + f[i - 1][j - 2] + f[i - 1][j - 3];
				break;
			case 5:
				f[i][j] = f[i - 1][j - 1] + f[i - 1][j - 2] + f[i - 1][j - 3] + 
                            f[i - 1][j - 4];
				break;
			case 6:
				f[i][j] = f[i - 1][j - 1] + f[i - 1][j - 2] + f[i - 1][j - 3] + 
                            f[i - 1][j - 4] + f[i - 1][j - 5];
				break;
			default:
				f[i][j] = f[i - 1][j - 1] + f[i - 1][j - 2] + f[i - 1][j - 3] + 
                            f[i - 1][j - 4] + f[i - 1][j - 5] + f[i - 1][j - 6];
			}
	return f[n][s];
}

动态规划,优化空间复杂度,只使用两个长度为s+1的数组,空间复杂度为O(s);

int times(int n, int s)
{
	vector<vector<int>> f(n + 1, vector<int>(s + 1, 0));
	for (int i = 1; i < 7; i++)
		f[1][i] = 1;
	for(int i = 2; i <= n; i++)
		for(int j = i; j <= s; j++)
			switch (j)
			{
			case 2 :
				f[i][j] = f[i - 1][j - 1];// +f[i - 1][j - 2];
				break;
			case 3:
				f[i][j] = f[i - 1][j - 1] + f[i - 1][j - 2]; // +f[i - 1][j - 3]
				break;
			case 4:
				f[i][j] = f[i - 1][j - 1] + f[i - 1][j - 2] + f[i - 1][j - 3];
				break;
			case 5:
				f[i][j] = f[i - 1][j - 1] + f[i - 1][j - 2] + f[i - 1][j - 3] +
                             f[i - 1][j - 4];
				break;
			case 6:
				f[i][j] = f[i - 1][j - 1] + f[i - 1][j - 2] + f[i - 1][j - 3] + 
                            f[i - 1][j - 4] + f[i - 1][j - 5];
				break;
			default:
				f[i][j] = f[i - 1][j - 1] + f[i - 1][j - 2] + f[i - 1][j - 3] + 
                            f[i - 1][j - 4] + f[i - 1][j - 5] + f[i - 1][j - 6];
			}
	return f[n][s];
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值