[英]How can I write a recursive function in R?
我如何編寫一個遞歸函數來獲取R中的combination(n,r)= combination(n-1,r-1)+ combination(n-1,r)? 我嘗試了以下代碼,但僅收到錯誤消息:
nCr=function(n, r) {
if (r == 0)
{
if (r == n) {
return (1)
} } else {
return (nCr(n-1, r-1) + nCr(n-1, r))
}
}
謝謝!
nCr <- function(n, r) {
if (r == 0 | r == n) return (1)
else return (nCr(n-1, r-1) + nCr(n-1, r))
}
nCr(20, 6)
[1] 38760
choose(20, 6)
[1] 38760
注意內置功能的性能。
system.time(for(i in 1:10) nCr(20, 6))
## user system elapsed
## 8.74 0.00 8.90
system.time(for(i in 1:10) choose(20, 6))
## user system elapsed
## 0 0 0
出現性能問題的部分原因是多次調用相同的輸入功能。 您可以通過緩存結果來使nCr
更快-此技術對許多遞歸函數很有用,盡管請注意,內置函數仍然要快得多。
library(memoise)
nCr2 <- memoise(nCr)
system.time(for(i in 1:10) nCr2(20, 6))
## user system elapsed
## 0.88 0.00 0.91
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.