等差数列

问题:
a个1,b个2,c个3,d个4
问当输入(a,b,c,d)时使其为若干个个数大于3的等差数列,并且没有剩余的数
比如(4,0,0,0)可以组成{1,1,1,1}没有剩余  返回true
(1,2,2,1)可以组成{1,2,3}  {2,3,4}没有剩余 返回true
(1,1,2,1)组成{1,2,3} 剩余{3,4}不满足 返回false
 
解题思路:
1. 如果分出一个123来,则(a,b,c,d)=====>(a-1,b-1,c-1,d)
2. 如果分出一个234来,则(a,b,c,d)=====>(a,b-1,c-1,d-1)
3. 如果分出一个1234来,则(a,b,c,d)=====>(a-1,b-1,c-1,d-1)
bool fun(int a, int b, int c, int d)
{
	if(a<0||b<0||c<0||d<0)
		return false;
	if((a>=3||a==0)&&(b>=3||b==0)&&(c>=3||c==0)&&(d>=3||d==0))
		return true;
	if(fun(a-1,b-1,c-1,d))
		return true;
	if(fun(a,b-1,c-1,d-1))
		return true;
	if(fun(a-1,b-1,c-1,d-1))
		return true;
	return false;
}

为避免数据过大导致栈溢出,修改为:

bool fun(int a, int b, int c, int d)
{
	if(a<0||b<0||c<0||d<0)
		return false;
	if((a>=3||a==0)&&(b>=3||b==0)&&(c>=3||c==0)&&(d>=3||d==0))
		return true;
	if(fun(a-1,b-1,c-1,d-1))
		return true;
	if(a<=d)
	{
		if(fun(a-1,b-1,c-1,d))
			return true;
		if(fun(a,b-1,c-1,d-1))
			return true;
	}
	else
	{
		if(fun(a,b-1,c-1,d-1))
			return true;
		if(fun(a-1,b-1,c-1,d))
			return true;
	}
	return false;
}

  

原文地址:https://www.cnblogs.com/Vae1990Silence/p/4508498.html