遞歸的一次簡單探討

在看某篇javascript文檔遞歸部分的時(shí)候,發(fā)現(xiàn)原本以為很熟悉的遞歸,其實(shí)還是有些地方做的不求甚解了,再細(xì)細(xì)看了下書中的代碼,倒是覺得挺有意思:

function findSolution(target) {
  function find(current, history) {
    if (current == target) {
      return history;
    } else if (current > target) {
      return null;
    } else {
      return find(current + 5, `(${history} + 5)`) ||
             find(current * 3, `(${history} * 3)`);
    }
  }
  return find(1, "1");
}

console.log(findSolution(24));
// → (((1 * 3) + 5) * 3)

順手就用python在實(shí)現(xiàn)了一遍, 發(fā)現(xiàn)作為動(dòng)態(tài)類型語言,兩者的確有某種異曲同工的地方

def findSolution(target):
    def find(current, history):

        if current == target: return history
        elif current > target: pass
        else:
            return find(current + 5, "({} + 5)".format(history)) or find(current*3,  "({}*3)".format(history))

    return find(1, "1")

print(findSolution(13))

因?yàn)樽罱诳磄olang相關(guān)方面的東西,所以想用go來實(shí)現(xiàn)一遍,結(jié)果就一直卡在這里大半天,靜態(tài)語言不熟悉,請大佬指導(dǎo)一下總算有一個(gè)大概的解法了

func findSolution(target int, current int, history string) (string, error){

    if current == target{
        return history, nil
    }else if current > target{
        return "", fmt.Errorf("no resulet")
    }else{
        rst, err := findSolution(target, current + 5, fmt.Sprintf("(%s + 5)", history))
        if err != nil {
            rst, err = findSolution(target, current*3, fmt.Sprintf("(%s * 3)", history))
        }
        return rst, err
    }
}

findSolution(13, 1, "1")

總結(jié)就是:動(dòng)態(tài)語言諸如python、ruby之類, 開發(fā)起來效率確實(shí)快,很多時(shí)候所思所想就是代碼實(shí)現(xiàn)
而golang之類的靜態(tài)語言,開發(fā)效率可能沒那么高,寫代碼的時(shí)候更多就是要思考、設(shè)計(jì)了, 但是勝在靜態(tài)語言本身的性能以及執(zhí)行效率可謂非常之高了

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Python語言特性 1 Python的函數(shù)參數(shù)傳遞 看兩個(gè)如下例子,分析運(yùn)行結(jié)果: 代碼一: a = 1 def...
    時(shí)光清淺03閱讀 556評論 0 0
  • Python語言特性 1 Python的函數(shù)參數(shù)傳遞 看兩個(gè)如下例子,分析運(yùn)行結(jié)果: 代碼一: a = 1 def...
    伊森H閱讀 3,175評論 0 15
  • 2018.2.22 在家辦公 年初七啦,按著國家假期的話,年初七是第一天上班的日子。大多數(shù)人都正常上班了,因?yàn)樽约?..
    陸嫻1983閱讀 185評論 0 0
  • 又到一年畢業(yè)季,又到一年分手季,但對于我來說,又到一年退伍季,又到一年送別季,這次的送別,雖然有退伍回家的,有考學(xué)...
    就是胡巴閱讀 277評論 0 1
  • 一、自我介紹三個(gè)標(biāo)簽: 1.兩個(gè)孩子寶媽 2.時(shí)間管理的踐行者 3.健康與美麗的追求者 90天三大目標(biāo): 1.易效...
    冰激凌317閱讀 383評論 1 0

友情鏈接更多精彩內(nèi)容