您的位置:首页 > 编程语言 > Java开发

一个算法问题的解决

2005-01-08 09:33 501 查看
在一个盒子里面有N个球,每次可以拿一个也可以拿二个,问:要把盒子里面的球拿
完,有多少种拿法!
1、(我自己的算法,比较复杂)
    直接通过排列组合得到的
   int n=N/2;
int Total=C(0,N)+C(1,(N-1))…+C(n,(N-n));
    其中的C(a,b)=b!/[a!(b-a)!]
验证:
   N=2: n=2/2=1; Total=C(0,2)+C(1,1)=1+1=2;
   N=3; n=3/2=1; Total=C(0,3)+C(1,2)=1+2=3;
   N=4; n=4/2=2; Total=C(0,4)+C(1,3)+C(2,2)=1+3+1=5;
   *****
/*
 * Created on 2004-11-19
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author Administrator
 *
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class Total {

 /**
  * 
  */
 public Total() {
  super();
  // TODO Auto-generated constructor stub
 }

 public static void main(String[] args) {
  int N = Integer.parseInt(args[0]);
  Total t = new Total();
  System.out.println("可以有"+t.count(N)+"种方法");
 }

 public int count(int N) {
  int sum = 0;
  int n = N / 2;
  for (int i = 0; i <= n; i++) {
   sum = sum + Count(i, (N - i));
  }
  return sum;
 }

 public int Count(int a, int b) {

  return (Step(b) / (Step(a) * (Step(b - a))));
 }

 public int Step(int n) {
  int result = 1;
  for (int i = 1; i <= n; i++) {
   result = result * i;
  }
  return result;
 }
}

2、看了看别人的算法,确实比我的要好的多
    设P(x)表示x个球时,不同的拿法,容易得到递归式:
 P(x) = P(x-1) + P(x-2) ( x > 2 )
 边界条件:
 P(1) = 1, P(2) = 2
 这样看来是Fibonacci数列了哈
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息