分治法加遞歸
class Solution(object):
? ? def helper(self, oper, j ,k):
? ? ? ? if oper=='+':
? ? ? ? ? ? return j+k
? ? ? ? elif oper=='-':
? ? ? ? ? ? return j-k
? ? ? ? else:
? ? ? ? ? ? return j*k
? ? def diffWaysToCompute(self, input):
? ? ? ? """
? ? ? ? :type input: str
? ? ? ? :rtype: List[int]
? ? ? ? """
? ? ? ? if input.isdigit():
? ? ? ? ? ? return [int(input)]
? ? ? ? res=[]
? ? ? ? for i in range(len(input)):
? ? ? ? ? ? if input[i] in "+-*":
? ? ? ? ? ? ? ? res1 = self.diffWaysToCompute(input[:i])
? ? ? ? ? ? ? ? res2 = self.diffWaysToCompute(input[i+1:])
? ? ? ? ? ? ? ? for j in res1:
? ? ? ? ? ? ? ? ? ? for k in res2:
? ? ? ? ? ? ? ? ? ? ? ? res.append(self.helper(input[i],j,k))
? ? ? ? return res
if input.isdigit():
return[int(input)]
遞歸
packagetest;publicclassStairs{/** * @authorCxl * @paramargs */publicstaticvoidmain(String[] args){intn =5;intmaxStep =3; System.out.println("方案數(shù):"+ getStepNum(n, maxStep)); }/** * * @authorCxl * @paramn 總的臺(tái)階數(shù) * @paramm 一次可以走的最大樓梯階數(shù) * @return*/privatestaticintgetStepNum(intn,intm){intsumStep =0;//總臺(tái)階數(shù)為0時(shí)零抬,終止遞歸循環(huán)if(n ==0) {return1; }if(n >= m) {//如果n大于每步最大臺(tái)階數(shù),則設(shè)置第一步為m之內(nèi)的一個(gè)臺(tái)階數(shù),然后遞歸循環(huán)for(inti =1; i <= m; i++) { sumStep += getStepNum(n - i, m); } }//如果n小于m巴比,則將一步最大臺(tái)階數(shù)縮小為n琢蛤,重新遞歸else{ sumStep = getStepNum(n, n); }returnsumStep; }}
sqrt
if x ==0;return 0
mid =left +(right-left)//2
twosum(hasmap)
鏈表交叉
先檢驗(yàn)邊界情況
if not head A or not headB:
? ? return None
詞異位
棧實(shí)現(xiàn)隊(duì)列