令人头疼的【动态规划】

题目一

令人头疼的【动态规划】_第1张图片

题目链接:https://leetcode-cn.com/problems/number-of-dice-rolls-with-target-sum/

解决方法

动态规划方法:
a[i][j] 表示i个骰子在目标为j时的组合数目
a[i][j] = a[i-1][j-1] + … + a[i-1][j-k] if (j-k >= 0)

//动态规划 
int numRollsToTarget(int d, int f, int target)
{
	const int mod = 1e9 + 7;
	
	int a[31][1001] = {{0}};
	for(int i = 0; i < d; i++)
	{
		for(int j = 0; j <= target; j++)
		{
			if(i == 0)
			{
				if(j >= 1 && j <= f)
					a[i][j] = 1;
			}
			else
			{
				for (int k = 1; k <= f && k < j; k++)
				{
					a[i][j] = (a[i][j] + a[i - 1][j - k]) % mod;
				}
			}
		}
	}
	return a[d - 1][target];
}

回溯法:超时了!!

int numRollsToTarget(int d, int f, int target)
{
	int rec = 0;
	int a[d];
	for(int i = 0; i < d; i++)
		a[i] = 1;
	
	int currentValue = d;
	while(true)
	{
		if(currentValue == target)
		{
			rec = (++rec) % 1000000007;
		}
		a[d - 1]++;
		if(a[d - 1] == f + 1 || currentValue >= target)
		{
			//回溯
			int j = d - 2;
			while(j >= 0 && a[j] == f)
			{
				j--;
			}
			if(j < 0)
				break;
			if(j >= 0)
			{
				a[j] = a[j] + 1;
				currentValue = 0;
				j++;
				while(j < d)
					a[j++] = 1;
				for(int jj = 0; jj < d; jj++)
					currentValue += a[jj]; 
			}
		}
		else
			currentValue++;
	}
	return rec;	
}

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