m个苹果放在n个筐里,每个筐至少一个,所有的筐都一样,有多少种放法

package com.study;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 
 * @author acer
 * @date 2014-09-15
 * 
 * m个苹果放在n个筐里,每个筐至少一个,所有的筐都一样,有多少种放法
 * 
 * 思路解析:
 * 		step1:每个筐里先放一个苹果,剩余m-n个苹果
 * 		step2:m-n个苹果最多放在m-n个筐里,由于所有的筐都认为是一样的,将筐编号为1-n,
 * 		       后面的筐里放的苹果必须大于等于前面筐里的苹果数。设剩余苹果数为left,剩余要
 * 		       放的筐为n,前一个筐里的苹果数为first。则每次放完当前一个后,向后继续放
 * 		递归函数:D(int first,int n,int left);
示例:8个苹果放入3个筐里
step1:每个筐先放一个,剩余5个
step2:5个苹果放到3个筐里,可能的方法为:(005)(014)(023)(113)(122)
 */
public class DistributeApple {

	public static int count=0;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		while(true){
			count=0;
			System.out.print("请输入苹果数:");
			InputStreamReader isr=new InputStreamReader(System.in);
			BufferedReader bf=new BufferedReader(isr);
			String numString=null;
			try {
				numString = bf.readLine().toString();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			int num1=Integer.parseInt(numString);
			
			System.out.print("请输入筐数:");
			try {
				numString=null;
				numString = bf.readLine().toString();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			int num2=Integer.parseInt(numString);
			
			
			DistributeApple da=new DistributeApple();
			if(num1>num2){						
				da.distributeApple(0, num2, num1-num2);		
			}else if(num1==num2){
				count++;
			}		
			System.out.println("一共有"+count+"种放法");
		}
	}
	
	public DistributeApple(){
		
	}
	
	void distributeApple(int first, int n, int left){
		//first:第一个筐的苹果数    n:筐的数量     left:剩余苹果	
		if(n==0){
			return;
		}else if(n==1){
			count++;
			System.out.println( first+"  "+ n+"   "+ left +"  "+count);
		
		}else{
			for(int k=first;k<=left/n;k++)				
				distributeApple(k,n-1,left-k);
		}
		
	}
	
	
	
}

转载于:https://www.cnblogs.com/wennian/p/5036926.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值