【算法】放苹果

 

递归解法

public class Main {
	//p:盘子数量 a:苹果数量
	public int putApple(int a,int p) {
		if(p > a) {
			return putApple(a,a); 
		}
		//分类 有盘子为空的放法
		//没有盘子为空的放法
		//先判断苹果是不是放完了
		if(a==0) 
			return 1;
		//如果盘子为空 ,没办法放 为0中
		if(p == 0)
			return 0;	
		else 
			return putApple( a,p-1) + putApple(a-p,p );//有盘子为空+没盘子为空	
	}
	// 测试代码
 	public static void main(String[] args) {
 		Main m  = new Main ();
 		System.out.println(m.putApple(7, 3));
	}
}

非递归的话 比较复杂一点点 用二维数组保存 然后一直加加到最后

猜你喜欢

转载自blog.csdn.net/kevin_nan/article/details/88065247