zoukankan      html  css  js  c++  java
  • 等差数列

    问题:
    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;
    }
    

      

  • 相关阅读:
    Python对象
    python 迭代器和生成器
    python中logging日志模块详解
    学习中遇到的一些问题(杂谈)
    如何在github上搜索项目
    python闭包与装饰器
    python面试题
    selenium
    python导入自定义包
    About Me、
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4508498.html
Copyright © 2011-2022 走看看