在看某篇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í)行效率可謂非常之高了