0
def comb(c: Int, r: Int): Int = {
      if(r == 1) c
      else if(r < c) comb(c-1, r-1) + comb(c-1, r)
      else 1
}
comb(20,10) //184,756

我想做的就是将其称为comb(10,20)并获得相同的结果。我尝试在签名中替换crrc,但它不起作用。

  def comb(c: Int, r: Int): Int = {
  if(c == 1) r
  else if(c < r) comb(r-1, c-1) + comb(r-1, c)
  else 1
  } 
  comb(10,20) //2 -> not right
4

2 回答 2

1

我要补充一点,不要害怕本地定义:

scala> def comb(c: Int, r: Int): Int = {
 |       if(r == 1) c
 |       else if(r < c) comb(c-1, r-1) + comb(c-1, r)
 |       else 1
 | }
comb: (c: Int, r: Int)Int

scala> comb(20,10) //184,756
res0: Int = 184756

scala> def cc(c: Int, r: Int): Int = {
     | def cc2(c: Int, r: Int): Int = {
     | if(r == 1) c
     | else if(r < c) comb(c-1, r-1) + comb(c-1, r)
     |  else 1
     | }
     | if (c < r) cc2(r,c) else cc2(c,r)
     | }
cc: (c: Int, r: Int)Int

scala> cc(20,10)
res1: Int = 184756

scala> cc(10,20)
res2: Int = 184756
于 2012-09-27T20:23:12.750 回答
1

需要更改子调用中的顺序:

def comb(c: Int, r: Int): Int = {
  if (c == 1) r
  else if (c < r) comb(c - 1, r - 1) + comb(c, r - 1)
  else 1
}

这给出了预期的结果:

comb(10, 20)  // 184756
于 2012-09-27T20:12:55.427 回答