组合:更改参数顺序

时间:2012-09-27 20:10:19

标签: scala recursion

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)并获得相同的结果。我尝试将c替换为r,将r替换为c,但签名除外,但不起作用。

  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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

我想补充一点,不要害怕本地的defs:

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