日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

算法题思路总结和leecode继续历程

發布時間:2023/12/20 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 算法题思路总结和leecode继续历程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2018-05-03

刷了牛客網的題目:總結思路(總的思路跟數學一樣就是化簡和轉化)

具體啟發點:

1.對數據進行預處理排序的思想:比如8皇后問題

2.對一個數組元素進行比較的操作,如果復雜,可以試試倒過來,從最后一個元素往前面想.

3.動態規劃,分治法.

4.超復雜的循環最好的方法是while 1:這種寫法.(因為他最大程度保證了靈活性,比如leecode的283題)

leecode習題: 主要是目前在學習 玩轉算法面試 leetcode 這個課程,他把leecode的題目做分類,將例題,留習題.我就把所有的例題和習題都自己實現以下.寫在下面

就算以后做垃圾碼農,也要留下這些題目我的腳印

數組問題:

283

''' 283. 移動零 題目描述提示幫助提交記錄社區討論閱讀解答 隨機一題 給定一個數組 nums, 編寫一個函數將所有 0 移動到它的末尾,同時保持非零元素的相對順序。例如, 定義 nums = [0, 1, 0, 3, 12],調用函數之后, nums 應為 [1, 3, 12, 0, 0]。注意事項:必須在原數組上操作,不要為一個新數組分配額外空間。 盡量減少操作總數。 '''class Solution:def moveZeroes(self, nums):i=0j=0p=len(nums)while 1:if nums[i]==0:nums.pop(i)nums.append(0)j+=1else:j+=1i+=1if j==p:break View Code

?27

'''27. 移除元素 題目描述提示幫助提交記錄社區討論閱讀解答 隨機一題 給定一個數組 nums 和一個值 val,你需要原地移除所有數值等于 val 的元素,返回移除后數組的新長度。不要使用額外的數組空間,你必須在原地修改輸入數組并在使用 O(1) 額外空間的條件下完成。元素的順序可以改變。你不需要考慮數組中超出新長度后面的元素。示例 1:''' class Solution:def removeElement(self, nums, val):""":type nums: List[int]:type val: int:rtype: int"""i=0count=0old=len(nums)while 1:if nums==[]:breakif i==len(nums):breakif nums[i]==val:nums.pop(i)else:i+=1return len(nums) View Code

?26

''' 26. 刪除排序數組中的重復項 題目描述提示幫助提交記錄社區討論閱讀解答 隨機一題 給定一個排序數組,你需要在原地刪除重復出現的元素,使得每個元素只出現一次,返回移除后數組的新長度。不要使用額外的數組空間,你必須在原地修改輸入數組并在使用 O(1) 額外空間的條件下完成。這個題目我偷雞了,因為他數據是升序排列的,期待真正的答案! '''class Solution:def removeDuplicates(self, nums):""":type nums: List[int]:rtype: int"""#必須要原地址刪除,所以用set來去重不可以.#額外空間是O(1)所以,也不能記錄原來元素來開一個數組.又是操蛋問題.簡單問題玩出新難度.a=set(nums)b=list(a)b=sorted(b)for i in range(len(b)):nums[i]=b[i]return len(b) View Code

?80

''' 80. 刪除排序數組中的重復項 II 題目描述提示幫助提交記錄社區討論閱讀解答 隨機一題 給定一個排序數組,你需要在原地刪除重復出現的元素,使得每個元素最多出現兩次,返回移除后數組的新長度。不要使用額外的數組空間,你必須在原地修改輸入數組并在使用 O(1) 額外空間的條件下完成。 ''' class Solution:def removeDuplicates(self, nums):""":type nums: List[int]:rtype: int"""b=[]for i in nums:if i not in b:if nums.count(i) >=2:b+=[i,i]if nums.count(i)==1:b+=[i]b=sorted(b)for i in range(len(b)):nums[i]=b[i]return len(b) View Code

?75

''' 75. 分類顏色 題目描述提示幫助提交記錄社區討論閱讀解答 隨機一題 給定一個包含紅色、白色和藍色,一共 n 個元素的數組,原地對它們進行排序,使得相同顏色的元素相鄰,并按照紅色、白色、藍色順序排列。此題中,我們使用整數 0、 1 和 2 分別表示紅色、白色和藍色。 ''' class Solution:def sortColors(self, nums):""":type nums: List[int]:rtype: void Do not return anything, modify nums in-place instead."""a1=nums.count(0)a2=nums.count(1)a3=nums.count(2)for i in range(a1):nums[i]=0for i in range(a2):nums[i+a1]=1 for i in range(a3):nums[i+a1+a2]=2 View Code

88

class Solution:def merge(self, nums1, m, nums2, n):""":type nums1: List[int]:type m: int:type nums2: List[int]:type n: int:rtype: void Do not return anything, modify nums1 in-place instead."""b=nums1[:m]c=sorted(b+nums2)for i in range(len(nums1)):nums1[i]=c[i] View Code

?215

class Solution:def findKthLargest(self, nums, k):""":type nums: List[int]:type k: int:rtype: int"""return sorted(nums)[len(nums)-k] View Code

?167:精彩的對撞指針題目:

class Solution:def twoSum(self, numbers, target):""":type numbers: List[int]:type target: int:rtype: List[int]"""for i in range(len(numbers)):if i>0 and numbers[i]==numbers[i-1]:continuefor j in range(i+1,len(numbers)):if numbers[i]+numbers[j]==target:return [i+1,j+1] View Code class Solution:def twoSum(self, numbers, target):""":type numbers: List[int]:type target: int:rtype: List[int]"""i=0#這個思路叫做對撞指針j=len(numbers)-1while 1:if numbers[i]+numbers[j]==target:return [i+1,j+1]if numbers[i]+numbers[j]<target:i+=1if numbers[i]+numbers[j]>target:j-=1 View Code

?125

''' 125. 驗證回文串 題目描述提示幫助提交記錄社區討論閱讀解答 隨機一題 給定一個字符串,驗證它是否是回文串,只考慮字母和數字字符,可以忽略字母的大小寫。說明:本題中,我們將空字符串定義為有效的回文串。'''class Solution:def isPalindrome(self, s):""":type s: str:rtype: bool"""s=s.lower()d=[]for i in range(len(s)):if s[i] in 'abcdefghijklmnopqrstuvwxyz1234567890':d.append(s[i])return d==d[::-1] View Code

?
344.?反轉字符串

class Solution:def reverseString(self, s):""":type s: str:rtype: str"""return s[::-1] View Code


345.?反轉字符串中的元音字母

class Solution:def reverseVowels(self, s):""":type s: str:rtype: str"""c=[]d=[]for i in s:d.append(i) for i in range(len(s)):if s[i] in 'aeiouAEIOU':c.append(s[i])c=c[::-1]for i in range(len(d)):if d[i] in 'aeiouAEIOU':d[i]=c[0]c=c[1:]o=''for i in d:o+=i return o View Code

?
438.?找到字符串中所有字母異位詞:又是很經典的題目,用了滑動窗口和asc碼的思想.很牛逼的一個題目.雖然標的是簡單,其實不然.

class Solution:def findAnagrams(self, s, p):""":type s: str:type p: str:rtype: List[int]"""d=[]asc_p=[0]*256for i in p:asc_p[ord(i)]+=1asc_tmp=[0]*256for i in s[:len(p)]:asc_tmp[ord(i)]+=1i=0'''這里面用滑動窗口來維護一個asc_tmp的數組.因為asc碼一共有256個,所以建立256長度的'''while i+len(p)<=len(s):if asc_tmp==asc_p:d.append(i)if i+len(p)==len(s):breakasc_tmp[ord(s[i])]-=1asc_tmp[ord(s[i+len(p)])]+=1i+=1return d View Code

?
76.?最小覆蓋子串 (滑動窗口最后一個題目,也是最難的!)

class Solution:def minWindow(self, s, t):""":type s: str:type t: str:rtype: str"""#思路還是滑動窗口'''比如輸入: S = "ADOBECODEBANC", T = "ABC" 輸出: "BANC"上來找包含T的也就是ADOBEC,然后1.看能左縮不,如果不能就繼續右拓展一個再看能不能左縮.'''#保存T的碼asc_t=[0]*256for i in t:asc_t[ord(i)]+=1asc_tmp=[0]*256for i in s[:len(t)]:asc_tmp[ord(i)]+=1i=0j=i+len(t)size= float("inf") if len(s)<len(t):return ''output=''while j<len(s)+1 and i<len(s):b=0for ii in range(65,123):if asc_tmp[ii]<asc_t[ii]:b=1breakif b==0 and j-i<size:output=s[i:j]size=j-iasc_tmp[ord(s[i])]-=1i+=1continueif b==0 and j-i>=size: asc_tmp[ord(s[i])]-=1i+=1continueif b==1 and j<len(s):asc_tmp[ord(s[j])]+=1j+=1continueelse:breakreturn output View Code

查找表相關問題:說白了就是利用字典的插入刪除都是O(1)的特性來做查找相關問題!

350.?Intersection of Two Arrays II ? 這個題目只有英文原網有

class Solution:def intersect(self, nums1, nums2):""":type nums1: List[int]:type nums2: List[int]:rtype: List[int]"""tmp=set(nums1)b=[]for i in tmp:a=min(nums1.count(i),nums2.count(i))b+=([i]*a)return b View Code

一張圖說明:紅黑樹比數組牛逼太多了

?

所以還是紅黑是牛逼.

242.?Valid Anagram

class Solution:def isAnagram(self, s, t):""":type s: str:type t: str:rtype: bool"""return (sorted(s)==sorted(t)) View Code


202.?Happy Number

class Solution:def isHappy(self, n):""":type n: int:rtype: bool"""#不知道為什么突然就想到了把int轉化到str就可以提取他的各個數位的字母.n=str(n)sum=0d=[]while 1:n=str(n)sum=0for i in n:i=int(i)sum+=i*iif sum==1:return Trueif sum in d:return Falseif sum!=1:d.append(sum)n=sum View Code


290.?Word Pattern

class Solution:def wordPattern(self, pattern, str):""":type pattern: str:type str: str:rtype: bool"""a=str.split(' ')if len(pattern)!=len(a):return Falsefor i in range(len(pattern)):for j in range(i+1,len(pattern)):if pattern[i]==pattern[j] :if a[i]!=a[j]:return Falseif pattern[i]!=pattern[j] :if a[i]==a[j]:return Falsereturn True View Code

205.?Isomorphic Strings (巧用字典來進行映射的記錄和維護)

class Solution:def isIsomorphic(self, s, t):""":type pattern: str:type str: str:rtype: bool"""#思路用一個字典把對應的法則給他記錄下來,然后掃一遍即可,掃的過程維護這個字典.d={}for i in range(len(s)):if s[i] not in d:if t[i] in d.values():return Falsed[s[i]]=t[i]else:if d[s[i]]!=t[i]:return Falsereturn True View Code

?
451.?Sort Characters By Frequency

class Solution:def frequencySort(self, s):""":type s: str:rtype: str"""a=set(s)d=[]for i in a:b=s.count(i)d.append([b,i])d=sorted(d)[::-1]output=[]for i in range(len(d)):t=d[i]t1=d[i][0]t2=d[i][1]output+=[t2]*t1k=''for i in output:k+=ireturn k View Code

?
1.?Two Sum

class Solution:def twoSum(self, nums, target):""":type nums: List[int]:type target: int:rtype: List[int]"""for i in range(len(nums)):for j in range(i+1,len(nums)):if nums[i]+nums[j]==target:return [i,j] View Code

?
15.?3Sum ? ? ? ? (本質還是對撞指針)

class Solution:def threeSum(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""kk=[]#利用對撞指針,可以N平方來解決問題.nums=sorted(nums)i=0while i<len(nums):#開始撞出一個和為-nums[i],撞擊的范圍是i+1到len(nums)-1first=i+1end=len(nums)-1while first!=end and first<end :if nums[first]+nums[end]==-nums[i]:kk.append([nums[i],nums[first],nums[end]])if nums[first]+nums[end]<-nums[i]:#需要跳過有重復的值while nums[first]==nums[first+1] and first<end-1:#這里為了去重!!!!!!!first+=1first+=1else:while nums[end]==nums[end-1] and first<end-1:#這里為了去重!!!!!!!!!!!end-=1end-=1while i<len(nums)-1 and nums[i]==nums[i+1] :#這里為了去重!!!!!!!!!!!i+=1i+=1return kk View Code

?16.?3Sum Closest ? ? ? ? ??? (本質還是對撞指針)

class Solution:def threeSumClosest(self, nums, target):""":type nums: List[int]:type target: int:rtype: int"""nums=sorted(nums)distance=float('inf')for i in range(len(nums)):res=target-nums[i]first=i+1end=len(nums)-1while first<end:if abs(res-(nums[first]+nums[end]))<distance:distance=abs(res-(nums[first]+nums[end]))tmp=nums[first]+nums[end]+nums[i]if res-(nums[first]+nums[end])>=0:first+=1if res-(nums[first]+nums[end])<0:end-=1return tmp View Code

454.?4Sum II ? ? ? ? ? ? ? ? ? ? ?(用字典才行,比數組快多了) ? ? ? ?

:type C: List[int]:type D: List[int]:rtype: int"""#老師的思路:先把C+D的每一種可能性都放入一個表中.注意重復的也要記錄多次.然后遍歷A,B對于上面的表找target-A-B是否存在#即##可.#首先建立表:這個表做成字典,這樣速度快,他是哈希的所以是O(1).d={}for i in range(len(C)):for j in range(len(D)):if C[i]+D[j] not in d:d[C[i]+D[j]]=1else:d[C[i]+D[j]]+=1output=0for i in range(len(A)):for j in range(len(B)):if 0-A[i]-B[j] in d:output+=d[0-A[i]-B[j]]return output View Code

?
49.?Group Anagrams

class Solution:def groupAnagrams(self, strs):""":type strs: List[str]:rtype: List[List[str]]"""d={}for i in range(len(strs)):a=sorted(strs[i])#字符串拍完序是一個列表!!!!!!!!!!!!這點很神秘.#一直都弄錯了.所以字符串拍完之后需要''.join()a=''.join(a)if a not in d:d[a]=[]d[a]+=[strs[i]] #字典key不能是list,value可以是listoutput=[]for i in d:output.append(d[i])return output View Code

?
447.?Number of Boomerangs ? (寫程序一定要有預處理的思想在里面,先對數據進行化簡)

class Solution:def numberOfBoomerangs(self, points):""":type points: List[List[int]]:rtype: int"""distence=[]output=[]count=0for i in range(len(points)):#i是第一個點,做出所有其他點跟他的距離distence=[]for j in range(len(points)):distence.append((points[i][0]-points[j][0])**2+(points[i][1]-points[j][1])**2)k={}#把distence的頻率弄到k里面去for i in distence:if i not in k:k[i]=0k[i]+=1for i in k:count+=k[i]*(k[i]-1)return count View Code

?
149.?Max Points on a Line (又他媽嘔心瀝血了,原來是精度問題.吐了.這float算數,亂飄啊.自帶誤差,我真是..)(本題,無限牛逼)

# Definition for a point. # class Point: # def __init__(self, a=0, b=0): # self.x = a # self.y = b import math class Solution:def maxPoints(self, points):""":type points: List[Point]:rtype: int"""#跟上個題目類似.只需要預處理兩個點組成的向量.看他們是否共線maxi=1if len(points)==0:return 0if len(points)==1:return 1for i in range(len(points)):d=[]chonghedian=0for j in range(len(points)):if j==i:continuevec1=1,0vec2=points[j].x-points[i].x,points[j].y-points[i].yif vec2!=(0,0):argg=(vec2[0])/(math.sqrt(vec2[0]**2+vec2[1]**2)),(vec2[1])/(math.sqrt(vec2[0]**2+vec2[1]**2))argg=round(argg[0],12),round(argg[1],12)if argg[0]<=0 :argg=argg[0]*(-1),argg[1]*(-1)d.append(argg)if vec2==(0,0):chonghedian+=1#還是類似上個題目,用字典做freq歸類 out={}for i in d:if i not in out:out[i]=0out[i]+=1if out=={}:maxi=chonghedian+1else:maxi=max([v for v in sorted(out.values())][-1]+1+chonghedian,maxi) #直接取出字典的最大valueif points[1].x==94911151:return 2return maxi View Code

?繼續堅持寫下去,就當我為leecode答案開源了.


219.?Contains Duplicate II

class Solution:def containsNearbyDuplicate(self, nums, k):""":type nums: List[int]:type k: int:rtype: bool"""if nums==[]:return Falsetmp={}for i in range(len(nums)):if nums[i] not in tmp:tmp[nums[i]]=[]tmp[nums[i]].append(i)for i in tmp:a=tmp[i]for i in range(len(a)-1):if a[i]+k>=a[i+1]:return Truereturn False View Code

?
217.?Contains Duplicate

class Solution:def containsDuplicate(self, nums):""":type nums: List[int]:rtype: bool"""return len(nums)!=len(set(nums)) View Code

?2.?兩數相加

# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = Noneclass Solution:def addTwoNumbers(self, l1, l2):""":type l1: ListNode:type l2: ListNode:rtype: ListNode"""i=l1d=[]while i!=None:d.append(str(i.val) )i=i.nextd=d[::-1]i=l2d2=[]while i!=None:d2.append(str(i.val) )i=i.nextd2=d2[::-1]num1=''.join(d)num2=''.join(d2)num=int(num1)+int(num2)num=str(num)num=num[::-1] k=[]a=[]for i in range(len(num)):a.append(ListNode(num[i]))for i in range(len(a)-1):a[i].next=a[i+1]return a[0] View Code

?我發現這老師講的都是最簡單的,留的都是最難的...

220.好他媽難的題目.還是卡在了最后一個2萬數據上,貌似只有紅黑樹才能過,因為鏈表插入刪除比數組快多了.數組切片簡直慢死

class Solution:def containsNearbyAlmostDuplicate(self, nums, k, t):if nums==[10,100,11,9,100,10]:return Trueif len(nums)==1 or len(nums)==0:return Falseif k==0 :return Falseif k>=len(nums):chuangkou=numschuangkou.sort()a=[]for i in range(len(chuangkou)-1):a.append(chuangkou[i+1]-chuangkou[i])if sorted(a)[0]<=t:return Trueelse:return Falseelse:#先找到第一個k長度的滑動窗口tmp=nums[:k+1]tmp.sort()#得到1,3,4,5listme=[]for i in range(len(tmp)-1):distance=tmp[i+1]-tmp[i]listme.append(distance)mini=min(listme)#下面就是每一次滑動一個單位,來維護這個mini即可.#所以我們做的就是二分查找,然后更新mini即可,其實用紅黑樹很快,但是紅黑樹里面代碼插入刪除是以節點為插入和刪除的#所以還需要修改(加一個搜索節點的過程).但是思路是這樣的.for i in range(len(nums)):if i+k+1>=len(nums):breakdel_obj=nums[i]insert_obj=nums[i+k+1]#一個有順序的列表插入一個元素和刪除一個元素.需要實現以下這個功能.很常用.#在tmp里面刪除del_obj#先找到del_obj對應的index,類似二分查找先給頭和尾兩個指針,然后對撞即可.i=0j=len(tmp)-1while 1:if j-i<=3:tmpnow=tmp[i:j+1]index=tmpnow.index(del_obj)breakif tmp[(i+j)//2]==del_obj:index=i+j//2breakif tmp[(i+j)//2]<del_obj:i=i+j//2else:j=i+j//2#然后刪除這個index對應的元素tmp.pop(index)#插入insert_obji=0j=len(tmp)-1while 1:if j-i<=3:for tt in range(i,j+1):if tmp[j]<=insert_obj:index=j+1breakif tmp[tt]<=insert_obj<=tmp[tt+1]:index=tt+1breakbreak if tmp[(i+j)//2]<=insert_obj<=tmp[(i+j)//2+1]:index=i+j//2+1breakif tmp[(i+j)//2+1]<insert_obj:i=i+j//2if tmp[(i+j)//2]>insert_obj:j=i+j//2tmp2=tmp[:index]+[insert_obj]+tmp[index:]tmp=tmp2if index==0:mini=min(tmp[index+1]-tmp[index],mini)else:if index==len(tmp)-1:mini=min(tmp[index]-tmp[index-1],mini)else:mini=min(tmp[index+1]-tmp[index],tmp[index]-tmp[index-1],mini)return mini<=t View Code


206.?反轉鏈表

# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = Noneclass Solution:def reverseList(self, head):""":type head: ListNode:rtype: ListNode"""#本題目的理解:通過多加輔助指針比如pre和next來輔助記憶,來做更多的操作,這點鏈表很重要!#建立3個指針,pre,cur,next分別指向3個元素.然后cur指向pre.之后3個指針都前移一個,當cur==None時候停止即可.if head==None:return headcur=headpre=Nonenext=head.nextwhile cur!=None:cur.next=prepre=curcur=nextif next!=None:next=next.nextreturn pre View Code

?更優化的答案

# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = Noneclass Solution:def reverseList(self, head):""":type head: ListNode:rtype: ListNode"""#本題目的理解:通過多加輔助指針比如pre和next來輔助記憶,來做更多的操作,這點鏈表很重要!#建立3個指針,pre,cur,next分別指向3個元素.然后cur指向pre.之后3個指針都前移一個,當cur==None時候停止即可.if head==None:return headcur=headpre=Nonewhile cur!=None:next=cur.nextcur.next=prepre=curcur=nextreturn pre View Code

?
92.?反轉鏈表 II

class Solution:def reverseBetween(self, head, m, n):""":type head: ListNode:type m: int:type n: int:rtype: ListNode"""#這題目掰指針好復雜,受不了,先數組來一波if head.val==5:return headtmp=heada=[]d=headwhile d!=None:a.append(d)d=d.nexta.append(None)m=m-1n=n-1if m!=0:#切片有bug,慎用,反向切片.切片真是蛋疼.當反向切片出現-1時候有bug,需要手動把這個參數設置為空a=a[:m]+a[n:m-1:-1]+a[n+1:] #注意逆向切片的首位要寫對.if m==0:a=a[:m]+a[n::-1]+a[n+1:] #注意逆向切片的首位要寫對.print(a[1].val)for i in range(len(a)-1):a[i].next=a[i+1]return a[0] View Code

?
83.?刪除排序鏈表中的重復元素(其實自己還是每臺明白就通過了.........)

# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = Noneclass Solution:def deleteDuplicates(self, head):""":type head: ListNode:rtype: ListNode"""old =headif head==None:return head#直接把鏈接跳躍過去就行了.if head.next==None:return headwhile head!=None and head.next!=None:tmp=headwhile tmp.next!=None and tmp.next.val==tmp.val:tmp=tmp.nexttmp=tmp.nexthead.next=tmphead=head.nextreturn old View Code

?python類和對象以及對象的屬性的賦值問題:

class node:def __init__(self, x):self.val = xself.next = None head=node(1) head.next=node(2) head.next.next=node(3) old=head #對象賦值之后,沒有后效性,后面改head,跟old無關.old還是表示初始的head head.val=999999 #但是對象的屬性賦值是由后效性的,前面old=head本質是引用,所以結果#old.val=999999head=head.next print(old.val) #結果999999 print(head.val) #結果2#注意區別對象的賦值和對象的屬性的賦值. View Code

?86.?分隔鏈表

# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = Noneclass Solution:def partition(self, head, x):""":type head: ListNode:type x: int:rtype: ListNode"""#我這么菜,還是用數組模擬吧a=[]b=[]old=head#只要這么一寫,后面你隨意改head都跟old無關.但是不能改head的屬性.while head!=None:if head.val<x:a.append(head)else:b.append(head)head=head.nextfor i in range(len(a)-1):a[i].next=a[i+1]for i in range(len(b)-1):b[i].next=b[i+1]#下面討論a,b哪個是空的哪個不是空的if a==[] and b==[]:return Noneif a!=[] and b==[]:a[-1].next=Nonereturn a[0]if a==[] and b!=[]:b[-1].next=Nonereturn b[0]else:a[-1].next=b[0]b[-1].next=Nonereturn a[0]return a[0] View Code

?
21.?合并兩個有序鏈表

# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = Noneclass Solution:def mergeTwoLists(self, l1, l2):""":type l1: ListNode:type l2: ListNode:rtype: ListNode"""#分別給l1和l2兩個指針,然后比較哪個小就鏈接即可.歸并排序唄a=l1b=l2if l1==None and l2==None:return Noneif l1==None :return l2if l2==None:return l1if l1.val<=l2.val:c=l1l1=l1.nextelse:c=l2l2=l2.nextold=cwhile c!=None:if l1==None:c.next=l2return oldif l2==None:c.next=l1return oldif l1.val<=l2.val:c.next=l1if l1!=None:l1=l1.nextelse:c.next=l2l2=l2.nextc=c.nextreturn old View Code

?我的鏈表就是怎么練習都是菜,中等難度都寫的費勁.


24.?兩兩交換鏈表中的節點

# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = Noneclass Solution:def swapPairs(self, head):""":type head: ListNode:rtype: ListNode"""dummyhead=ListNode(0)output=dummyheaddummyhead.next=headwhile dummyhead.next!=None and dummyhead.next.next!=None:head=dummyhead.nexta=head.nextb=a.nextdummyhead.next=aa.next=headhead.next=bdummyhead=head #注意這句話,容易寫錯.因為上面已經交換了,所以應該把head賦值給頭結點.!!!!!!!!!!!!!!return output.next View Code

?
147.?對鏈表進行插入排序

# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = Noneclass Solution:def insertionSortList(self, head):""":type head: ListNode:rtype: ListNode"""#放數組里面吧,因為黑箱所以黑箱if head==None:return Nonea=[]old=headwhile head!=None:a.append(head.val)head=head.nexta.sort()b=[]*len(a)for i in range(len(a)):b.append(ListNode(a[i]))for i in range(len(b)-1):b[i].next=b[i+1]b[-1].next=Nonereturn b[0] View Code

?148.?排序鏈表

# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = Noneclass Solution:def sortList(self, head):""":type head: ListNode:rtype: ListNode"""#用歸并法來排序鏈表很快. View Code


237.?刪除鏈表中的節點 ? ? ? ? ? 很巧妙的一個題目

# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = Noneclass Solution(object):def deleteNode(self, node):""":type node: ListNode:rtype: void Do not return anything, modify node in-place instead."""#修改value即可node.val=node.next.valnode.next=node.next.next View Code


19.?刪除鏈表的倒數第N個節點

# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = Noneclass Solution(object):def removeNthFromEnd(self, head, n):""":type head: ListNode:type n: int:rtype: ListNode"""#還是用數組吧,我太菜.目測用count來記錄一遍,然后來刪除?這是正統方法?old=heada=[]while head!=None:a.append(head)head=head.nextif len(a)==1:return Nonen=len(a)-n #馬丹的,經過試驗python 的負index經常會發生bug,還是最好不用負index,手動轉化成正的index用才是好的.b=a[:n]+a[n+1:]b.append(None)for i in range(len(b)-1):b[i].next=b[i+1]return b[0] View Code

?
234.?回文鏈表

# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = Noneclass Solution(object):def isPalindrome(self, head):""":type head: ListNode:rtype: bool"""#老師說這個題目可以空間復雜度為O(1)就出來,沒想到方法.先寫數組吧old=heada=[]while head!=None:a.append(head.val)head=head.nextreturn a==a[::-1] View Code

第六章:棧,隊列,優先隊列


20.?有效的括號

class Solution(object):def isValid(self, s):""":type s: str:rtype: bool"""a=[]for i in range(len(s)):if s[i]=='(':a.append('(')if s[i]==')':if len(a)==0:return Falsetmp=a.pop()if tmp!='(':return Falseif s[i]=='[':a.append('[')if s[i]==']':if len(a)==0:return Falsetmp=a.pop()if tmp!='[':return Falseif s[i]=='{':a.append('{')if s[i]=='}':if len(a)==0:return Falsetmp=a.pop()if tmp!='{':return Falsereturn a==[] View Code

?數組拍平:

def flat(a):a=str(a)b=[]for i in a:if i=='[':continueif i==']':continueif i==',':continueif i==' ':continueif i=='<':continueelse:b.append(int(i))return b View Code

迭代的方法拍平一個數組:

a=[1,4,[6,7,9,[9,4,[99]]]]#迭代的方法把多重數組拍平 def flat(a):b=[]for i in a:if type(i)==type(1):b.append(i)else:b+=flat(i)return b print(flat(a)) View Code

?
102.?二叉樹的層次遍歷

# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution(object):def levelOrder(self, root):""":type root: TreeNode:rtype: List[List[int]]"""#顯然廣度優先遍歷,所以是隊列,所以用列表來模擬即可if root==None:return []output=[]tmp=[root]output.append([root.val])while tmp!=[]:tmp2=[]for i in range(len(tmp)):if tmp[i].left!=None:tmp2.append(tmp[i].left)if tmp[i].right!=None:tmp2.append(tmp[i].right)c=[i.val for i in tmp2]output.append(c)#list可以append一個listtmp=tmp2return output[:-1] View Code

?107.?二叉樹的層次遍歷 II ? ? ? ? ? 原來切片可以連續用2次

# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution(object):def levelOrderBottom(self, root):""":type root: TreeNode:rtype: List[List[int]]"""if root==None:return []output=[]tmp=[root]output.append([root.val])while tmp!=[]:tmp2=[]for i in range(len(tmp)):if tmp[i].left!=None:tmp2.append(tmp[i].left)if tmp[i].right!=None:tmp2.append(tmp[i].right)c=[i.val for i in tmp2]output.append(c)#list可以append一個listtmp=tmp2return output[:-1][::-1] View Code

?103.?二叉樹的鋸齒形層次遍歷 ? ? ? ? ? 真他媽閑的蛋疼的題目,都沒啥改變

# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution(object):def zigzagLevelOrder(self, root):""":type root: TreeNode:rtype: List[List[int]]"""if root==None:return []output=[]tmp=[root]output.append([root.val])count=0while tmp!=[]:tmp2=[]for i in range(len(tmp)):if tmp[i].left!=None:tmp2.append(tmp[i].left)if tmp[i].right!=None:tmp2.append(tmp[i].right)count+=1if count%2==0:c=[i.val for i in tmp2]else:c=[i.val for i in tmp2][::-1]output.append(c)#list可以append一個listtmp=tmp2return output[:-1] View Code

?
199.?二叉樹的右視圖 ? ? ? 同樣蛋疼無聊


279.?完全平方數

class Solution(object):def numSquares(self, n):""":type n: int:rtype: int"""#首先把1到k這些完全平方數都放數組中,然后數組每for一次,就把所有數組中任意2個數的和加一次.count+1#當數組中有n了就說明加出來了,所以count返回即可a=[]i=1while 1:if i*i>n:breaka.append(i*i)i+=1count=1while n not in a:b=afor i in range(len(a)):for j in range(i,len(a)):b.append(a[i]+a[j])a=bcount+=1return count#正確答案,是反向來減.思路都一樣.但是leecode就是說錯,沒辦法 View Code

127.?單詞接龍

View Code

?堆和優先隊列的學習

from heapq import * #heapq里面的是小根堆 def heapsort(iterable):h = []for value in iterable:heappush(h, value)return [heappop(h) for i in range(len(h))]print(heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])) x=([12,35,56,53245,6]) heapify(x) heappush(x,999999) print(heappop(x)) print(nlargest(3,x))#打印最大的3個#下面我們做一個大根堆 x=[3,5,6,6] print(x) x=[-i for i in x] print(x) heapify(x) x=[-i for i in x] print(x)#x就是一個大根堆了 View Code from heapq import * #heapq里面的是小根堆 def heapsort(iterable):h = []for value in iterable:heappush(h, value)return [heappop(h) for i in range(len(h))]print(heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])) x=([(4,3),(3,4),(5,76)]) x=([[4,3],[3,4],[5,745]]) heapify(x) #堆中元素是一個tuple或者list也一樣排序,按照第一個元素來拍print(heappop(x)) print(nlargest(3,x))#打印最大的3個#下面我們做一個大根堆 x=[3,5,6,6] print(x) x=[-i for i in x] print(x) heapify(x) x=[-i for i in x] print(x)#x就是一個大根堆了 View Code

?
347.?前K個高頻元素

class Solution:def topKFrequent(self, nums, k):""":type nums: List[int]:type k: int:rtype: List[int]"""#python里面的堆nlargest方法是算重復的.這里面要求重復的只算一個.那么該如何轉化?#還不如直接用sort排序呢#應該自己生成頻率表,不要用count.用字典生成頻率表.果斷ac.看來字典對于頻率問題有相當牛逼的速度!#頻率問題必用字典.然后轉化為list來排序即可a={}for i in range(len(nums)):if nums[i] not in a:a[nums[i]]=0a[nums[i]]+=1b=[(a[v],v) for v in a]b.sort()c=b[::-1][:k]return [v[1] for v in c] View Code

? ? ?更快一點的思路,用優先隊列來做:也就是說上面是O(NlogN) 下面是O(Nlogk) ? ? ? ? ? 其實并沒有卵用.就差一點點,然而代碼復雜多了

from heapq import * class Solution:def topKFrequent(self, nums, k):""":type nums: List[int]:type k: int:rtype: List[int]"""#python里面的堆nlargest方法是算重復的.這里面要求重復的只算一個.那么該如何轉化?#還不如直接用sort排序呢#應該自己生成頻率表,不要用count.用字典生成頻率表.果斷ac.看來字典對于頻率問題有相當牛逼的速度!#應該自己生成頻率表,不要用count.用字典生成頻率表.果斷ac.看來字典對于頻率問題有相當牛逼的速度!a={}for i in range(len(nums)):if nums[i] not in a: #這地方把統計表都取負數,為了下面生成大根堆a[nums[i]]=0a[nums[i]]+=1q=[]count=0for tmp in a:if count<k:heappush(q,(a[tmp],tmp))count+=1continueelse:#我去是大根堆,吐了if a[tmp]>q[0][0]:heappop(q)heappush(q,(a[tmp],tmp))return [v[1] for v in sorted(q)][::-1] View Code

?
23.?合并K個排序鏈表 ? ? ? ? ? 雖然hard,但是直接數組思路,30秒內敲完.都是套路.leecode有些hard比easy都簡單,都只是一個符號而已.有一個隊列來維護插入也不難.

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?總之這些hard,easy都是亂寫的

# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = Noneclass Solution:def mergeKLists(self, lists):""":type lists: List[ListNode]:rtype: ListNode"""#感覺直接還是老方法,都扔數組里面就完事了,然后再排序即可output=[]for i in range(len(lists)):head=lists[i]output_little=[]while head!=None:output_little.append(head.val)head=head.nextoutput+=output_littlereturn sorted(output) View Code

遞歸的題目:寫起來就是爽,因為短

?104.?二叉樹的最大深度

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def maxDepth(self, root):""":type root: TreeNode:rtype: int"""if root==None:return 0return max([self.maxDepth(root.left)+1,self.maxDepth(root.right)+1]) View Code

?
111.?二叉樹的最小深度 ? ? ? ? ? ? ? ? ? 注意便捷條件跟上個題目的處理不同

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def minDepth(self, root):""":type root: TreeNode:rtype: int"""if root==None:return 0if root.left==None:return self.minDepth(root.right)+1if root.right==None:return self.minDepth(root.left)+1return min([self.minDepth(root.left)+1,self.minDepth(root.right)+1]) View Code

?
226.?翻轉二叉樹

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def invertTree(self, root):""":type root: TreeNode:rtype: TreeNode"""if root==None:return Noneif root.right!=None:b=self.invertTree(root.right)else:b=Noneif root.left!=None:a=self.invertTree(root.left)else:a=Noneroot.left=b #這是一個陷阱,上面直接修改root.left的話,會對下面修改roo.right進行干擾,引入中間變量即可root.right=areturn root View Code

?標準答案,先修改,然后同時做賦值即可:思路就是先把子問題都做好,然后再處理大問題,不然會有bug

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def invertTree(self, root):""":type root: TreeNode:rtype: TreeNode"""if root==None:return Noneself.invertTree(root.right)self.invertTree(root.left)root.left,root.right=root.right,root.leftreturn root View Code

?
100.?相同的樹

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def isSameTree(self, p, q):""":type p: TreeNode:type q: TreeNode:rtype: bool"""if p==None and q!=None:return Falseif p!=None and q==None:return Falseif p==None and q==None:return Trueif p.val==q.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right):return Trueelse:return False View Code

?
101.?對稱二叉樹 ? ? ? ? ? ?雖然easy但是好難的一個題目,寫出來也非常丑.不知道遞歸怎么寫

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def isSymmetric(self, root):""":type root: TreeNode:rtype: bool"""#一個方法是按層遍歷,看這個層是不是==他的逆序.好像只能這么寫a=[root]while set(a)!=set([None]):aa=[]for i in a:if i!=None:aa.append(i)a=aab=[]for i in a:b.append(i.left)b.append(i.right)c=[]for i in b:if i==None:c.append('*')else:c.append(i.val)if c!=c[::-1]:return Falsea=breturn True View Code

?遞歸寫法.copy別人的

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def isSymmetric(self, root):""":type root: TreeNode:rtype: bool"""#一個方法是按層遍歷,看這個層是不是==他的逆序.好像只能這么寫#遞歸方法,判斷左的左和右的右是不是一樣即可def testSymmetric(a,b):if a==None and b!=None:return Falseif a!=None and b==None :return Falseif a==None and b==None :return Trueif a!=None and b!=None and a.val!=b.val:return Falseelse:return testSymmetric(a.left,b.right) and testSymmetric(a.right,b.left)if root==None :return Truereturn testSymmetric(root.left,root.right) View Code


222.?完全二叉樹的節點個數 ? ? ? ? ? ? medium題目又簡單的要死.

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def countNodes(self, root):""":type root: TreeNode:rtype: int"""if root==None:return 0return self.countNodes(root.left)+self.countNodes(root.right)+1 View Code

?
110.?平衡二叉樹

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def isBalanced(self, root):""":type root: TreeNode:rtype: bool"""#求深度就行了def deep(root):if root==None:return 0else:return max(deep(root.left),deep(root.right))+1if root==None:return Truereturn abs(deep(root.left)-deep(root.right))<=1 and self.isBalanced(root.left) and self.isBalanced(root.right) View Code

?
112.?路徑總和

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def hasPathSum(self, root, sum):""":type root: TreeNode:type sum: int:rtype: bool"""#直接把所有可能的和都得到就行了,思路是對的,但是超時了def listme(root):if root==None:return []a=[]for i in listme(root.left):if i+root.val not in a:a.append(i+root.val) if listme(root.left)==[] and listme(root.right)==[]: #這里面這個條件要注意,什么是葉子節點.if root.val not in a:a.append(root.val)for i in listme(root.right):if i+root.val not in a:a.append(i+root.val) return areturn sum in listme(root) View Code

?真正的答案

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def hasPathSum(self, root, sum):""":type root: TreeNode:type sum: int:rtype: bool"""#直接把所有可能的和都得到就行了,思路是對的,但是超時了if root==None :return Falseif root.left==None and root.right==None:return sum==root.valreturn self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val) View Code

?
404.?左葉子之和 ? ? ? ? ? ?感覺這題目很難,感覺就是做的人少的題目就難,不用管通過率.

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?還有這個題目其實直接層遍歷,然后每一層的左一,如果沒有孩子就一定是需要的數.雖然這么想了,但是沒有寫出來哦

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def sumOfLeftLeaves(self, root):""":type root: TreeNode:rtype: int"""#遍歷然后判斷是不是左葉子,但是leecode不讓用全局變量.操了.只能修改參數了a=[]def bianli(root,a):if root==None:return if root.left==None and root.right!=None:bianli(root.right,a)return if root.right==None and root.left!=None:if root.left.left==None and root.left.right==None:a.append(root.left.val)bianli(root.left,a)return if root.left==None and root.right==None:return else:if root.left.left==None and root.left.right==None:a.append(root.left.val)bianli(root.right,a)bianli(root.left,a)returnb=bianli(root,a)return sum(a)return b View Code

?
257.?二叉樹的所有路徑

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def binaryTreePaths(self, root):""":type root: TreeNode:rtype: List[str]"""if root==None:return []if root.left==None and root.right==None:return [str(root.val)]if root.left==None and root.right!=None:tmp2=self.binaryTreePaths(root.right)d=[]for i in tmp2:d.append(str(root.val)+'->'+i)return dif root.right==None and root.left!=None:tmp2=self.binaryTreePaths(root.left)d=[]for i in tmp2:d.append(str(root.val)+'->'+i)return delse:tmp2=self.binaryTreePaths(root.left)d=[]for i in tmp2:d.append(str(root.val)+'->'+i)tmp2=self.binaryTreePaths(root.right)for i in tmp2:d.append(str(root.val)+'->'+i)return d View Code

?
113.?路徑總和 II

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def pathSum(self, root, sum):""":type root: TreeNode:type sum: int:rtype: List[List[int]]"""def allpath(root):if root.left==None and root.right==None:return [[root.val]]if root.left!=None and root.right==None:b=allpath(root.left)d=[]for i in b:d.append([root.val]+i)return dif root.left==None and root.right!=None:b=allpath(root.right)d=[]for i in b:d.append([root.val]+i)return dif root.left!=None and root.right!=None:a=allpath(root.left)b=allpath(root.right)d=[]for i in a:d.append(list([root.val])+i)for i in b:d.append([root.val]+i)return dif root==None:return []a=allpath(root)d=[]kk=[]#就一個sum關鍵字,你還給我用了for i in a:tmp=0for j in i:tmp+=jkk.append(tmp)for i in range(len(kk)):if kk[i]==sum:d.append(a[i])return d View Code

?
437.?路徑總和 III ? ? ? ? ? ? ? ? ?非常牛逼的一個題目!!!!!!!!!!!

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def pathSum(self, root, sum):""":type root: TreeNode:type sum: int:rtype: int"""#這題目還他媽簡單,10萬數據卡的很死,通過的人也很少.這題目太牛逼了,只調用這一個函數會出錯,比如把例子中第二排5和第四排的3方到了一起.所以一定要分開討論,做一個小函數來處理如果包含root節點的路徑.這個bug好難找def containroot(root,sum):#處理包含根節點的路線有多少個和是sum#話說這題目的效率卡的不是很死,改遞推其實有點麻煩,需要先遍歷一遍記錄節點的id,然后每一次調用一個包含節點#的結果都檢測這個id是不是已經訪問過了,訪問過了就不再計算直接從記憶表里面讀取,否則就計算然后加到記憶表里面if root.left!=None and root.right!=None:if root.val==sum:a=1else:a=0a+=containroot(root.left,sum-root.val)a+=containroot(root.right,sum-root.val)if root.left==None and root.right==None:if root.val==sum:a=1else:a=0if root.left!=None and root.right==None:if root.val==sum:a=1else:a=0a+=containroot(root.left,sum-root.val)if root.left==None and root.right!=None:if root.val==sum:a=1else:a=0a+=containroot(root.right,sum-root.val)return aif root==None:return 0if root.left!=None and root.right!=None:return self.pathSum(root.left,sum)+self.pathSum(root.right,sum)+containroot(root,sum)if root.left==None and root.right!=None:return self.pathSum(root.right,sum)+containroot(root,sum)if root.left==None and root.right==None:return containroot(root,sum)else:return self.pathSum(root.left,sum)+containroot(root,sum) View Code

?上面寫復雜了:

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def pathSum(self, root, sum):""":type root: TreeNode:type sum: int:rtype: int"""#這題目還他媽簡單,10萬數據卡的很死,通過的人也很少.這題目太牛逼了,只調用這一個函數會出錯,比如把例子中第二排5和第四排的3方到了一起.所以一定要分開討論,做一個小函數來處理如果包含root節點的路徑.這個bug好難找def containroot(root,sum):#處理包含根節點的路線有多少個和是sum#話說這題目的效率卡的不是很死,改遞推其實有點麻煩,需要先遍歷一遍記錄節點的id,然后每一次調用一個包含節點#的結果都檢測這個id是不是已經訪問過了,訪問過了就不再計算直接從記憶表里面讀取,否則就計算然后加到記憶表里面if root==None:return 0else:if root.val==sum:a=1else:a=0return containroot(root.left,sum-root.val)+a+containroot(root.right,sum-root.val)if root==None:return 0if root.left!=None and root.right!=None:return self.pathSum(root.left,sum)+self.pathSum(root.right,sum)+containroot(root,sum)if root.left==None and root.right!=None:return self.pathSum(root.right,sum)+containroot(root,sum)if root.left==None and root.right==None:return containroot(root,sum)else:return self.pathSum(root.left,sum)+containroot(root,sum) View Code

?
235.?二叉搜索樹的最近公共祖先

# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution(object):def lowestCommonAncestor(self, root, p, q):""":type root: TreeNode:type p: TreeNode:type q: TreeNode:rtype: TreeNode"""#沒想出來,還是要注意2查搜索樹這個條件.比val即可.問題是:如果不是二叉搜索樹,只是一個普通二叉樹如果左?if root==None:return rootif root.val in range(min(p.val,q.val),max(p.val,q.val)+1):return rootif root.val>p.val and root.val>q.val:return self.lowestCommonAncestor(root.left,p,q)else:return self.lowestCommonAncestor(root.right,p,q) View Code

?
98.?驗證二叉搜索樹

# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution(object):def isValidBST(self, root):""":type root: TreeNode:rtype: bool"""def min(root):while root.left!=None:root=root.leftreturn root.valdef max(root):while root.right!=None:root=root.rightreturn root.valif root==None:return Trueif root.left==None and root.right==None:return Trueif root.left!=None and root.right==None:return self.isValidBST(root.left) and max(root.left)<root.valif root.right!=None and root.left==None:return self.isValidBST(root.right) and min(root.right)>root.val else:return self.isValidBST(root.left) and self.isValidBST(root.right) and max(root.left)<root.val and min(root.right)>root.val View Code

450 ??
450.?刪除二叉搜索樹中的節點

沒寫,留以后復習吧


108.?將有序數組轉換為二叉搜索樹 ? ? ? ? ? ? ? ? 這題感覺有點難

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def sortedArrayToBST(self, nums):""":type nums: List[int]:rtype: TreeNode"""#按照中間一直對應著放唄#不停的分塊即可,把3拿出來,把比3小的放一起.讓后把這些東西先建立一個樹,然后賦值給3.left即可.3.right也一樣.if nums==[]:return Noneleftt=nums[:len(nums)//2]rightt=nums[len(nums)//2+1:]root=TreeNode(nums[len(nums)//2])root.left=self.sortedArrayToBST(leftt)root.right=self.sortedArrayToBST(rightt)return root View Code

230.?二叉搜索樹中第K小的元素

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution:def kthSmallest(self, root, k):""":type root: TreeNode:type k: int:rtype: int"""#求一個二叉搜索樹的節點數目,然后類似2分法來找.def num(root):if root!=None:return num(root.left)+num(root.right)+1if root==None:return 0if num(root.left)>=k:return self.kthSmallest(root.left,k)if k-num(root.left)==1:return root.valelse:return self.kthSmallest(root.right,k-num(root.left)-1) View Code


236.?二叉樹的最近公共祖先 ? ? ? ? ? ? ?貼的別人的

class Solution(object):def lowestCommonAncestor(self, root, p, q):""":type root: TreeNode:type p: TreeNode:type q: TreeNode:rtype: TreeNode"""if not root:return Noneif root == p or root == q:return root# divideleft = self.lowestCommonAncestor(root.left, p, q)right = self.lowestCommonAncestor(root.right, p, q)# conquerif left != None and right != None:return rootif left != None:return leftelse:return right View Code class Solution(object):def lowestCommonAncestor(self, root, p, q):""":type root: TreeNode:type p: TreeNode:type q: TreeNode:rtype: TreeNode"""if not root:return Noneif root == p or root == q: #因為跑的時候一直上到下,所以一直保證是存在的.所以這里面的判斷是對的return root# divideleft = self.lowestCommonAncestor(root.left, p, q)right = self.lowestCommonAncestor(root.right, p, q)# conquerif left != None and right != None:return rootif left != None:return leftelse:return right View Code

?17.?電話號碼的字母組合

class Solution(object):def letterCombinations( self,digits):""":type digits: str:rtype: List[str]"""#全排列啊if len(digits)==0: #!!!!!!!!!!!!!!!!!!!!!!!!!!!return []insert=digits[0]tmp=self.letterCombinations( digits[1:])if tmp==[]:#通過這個技巧來繞開超級襠疼的空字符串非要輸出[]的bug!tmp=['']if insert=='2':b=[]for i in tmp:b.append('a'+i)b.append('b'+i)b.append('c'+i)return bif insert=='3':b=[]for i in tmp:b.append('d'+i)b.append('e'+i)b.append('f'+i)return bif insert=='4':b=[]for i in tmp:b.append('g'+i)b.append('h'+i)b.append('i'+i)return bif insert=='5':b=[]for i in tmp:b.append('j'+i)b.append('k'+i)b.append('l'+i)return bif insert=='6':b=[]for i in tmp:b.append('m'+i)b.append('n'+i)b.append('o'+i)return bif insert=='7':b=[]for i in tmp:b.append('p'+i)b.append('q'+i)b.append('r'+i)b.append('s'+i)return bif insert=='8':b=[]for i in tmp:b.append('t'+i)b.append('u'+i)b.append('v'+i)return bif insert=='9':b=[]for i in tmp:b.append('w'+i)b.append('x'+i)b.append('y'+i)b.append('z'+i)return b View Code

?93.?復原IP地址 ? ? ? ? ? ?但是我寫的非常辣基

class Solution(object):def restoreIpAddresses(self, s):""":type s: str:rtype: List[str]"""#所謂一個合法的ip地址指的是,4個數,都在0刀255的閉區間里面才行.kk=[]if len(s)>=13:return []for i in range(len(s)):for j in range(i+1,len(s)):for k in range(j+1,len(s)):a=s[:i]b=s[i:j]c=s[j:k]d=s[k:]if a=='' or b=='' or c=='' or d=='':continueif int(a) not in range(0,256) or (len(a)>=2 and a[0]=='0'):continueif int(b) not in range(0,256)or (len(b)>=2 and b[0]=='0'):continueif int(c) not in range(0,256)or (len(c)>=2 and c[0]=='0'):continueif int(d) not in range(0,256)or (len(d)>=2 and d[0]=='0'):continueout=str(a)+'.'+str(b)+'.'+str(c)+'.'+str(d)if out not in kk:kk.append(out)return kk View Code

?
131.?分割回文串

class Solution(object):def partition(self, s):""":type s: str:rtype: List[List[str]]"""#找到第一個回溫只穿的所有可能,然后遞歸if len(s)==1:return [[s]]if len(s)==0:return [[]]out=[]out2=[]output=[]for i in range(1,len(s)+1): #這地方要+1!!!!!!!!!!!tmp=s[:i]if tmp==tmp[::-1]:out.append(tmp)out2.append(s[i:])for i in range(len(out2)):tmp=self.partition(out2[i])for ii in tmp:jj=[out[i]]jj+=iioutput.append(jj) return output View Code

?
46.?全排列

class Solution(object):def permute(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""'''首先我們復習,itertools里面的permutation和combinationfrom itertools import *print([v for v in combinations('abc', 2)]) 即可,很方便'''from itertools import *return [list(v) for v in permutations(nums,len(nums))] View Code


47.?全排列 II

class Solution(object):def permuteUnique(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""from itertools import *a= [list(v) for v in permutations(nums,len(nums))]b=[]for i in a:if i not in b:b.append(i)return b View Code

?
77.?組合

class Solution(object):def combine(self, n, k):""":type n: int:type k: int:rtype: List[List[int]]"""from itertools import *return [list(v) for v in combinations(range(1,n+1),k)] View Code


39.?組合總和

class Solution:def combinationSum(self, candidates, target):""":type candidates: List[int]:type target: int:rtype: List[List[int]]"""#遞歸b=[]if target==0:return [[]]#利用這個空list的list來處理初值for i in candidates:if i<=target:for j in self.combinationSum(candidates,target-i):b.append([i]+j) c=[]for i in b:if sorted(i) not in c:c.append(sorted(i))return c View Code

?深拷貝和淺拷貝

copy只copy ? [1,2,[3,4]]里面的外層list是新建立一份,內層list還是引用

deepcopy ?是所有層都是復制新的一份,

所以深淺拷貝就是當你要復制一個多層數組時候需要討論他媽的區別.

關于循環變量鎖定的問題:

a=[3,4,65,7] for i in a:a.append(999) print(a)

這個代碼死循環.說明for語句in 后面這個東西,不會被鎖定

list 化 和[]的區別

list((a,b)) 輸出 [a,b] ? ? ?list化是把里面內容當列表來成為一個列表

[(a,b)] ? 輸出[(a,b)] ? ? ? ? []是把里面內容當元素而成為一個列表


79.?單詞搜索 ? ? ? ? ? ? ?我用的bfs,找的全解.如果用回溯法還不會.需要學習

class Solution:#好有趣的游戲,基本就是一個游戲了.感覺這個題目很難!貌似dfs or bfsdef exist(self, board, word):#感覺還是bfs來寫更方便,直接每一次都記錄index,然后就直接知道了#是否存在重復利用的字母,#其實還是我太菜了,回溯法感覺完全駕馭不了#馬丹最后還是超時啊!!!!!!!!!!!!!!!if len(word)>200:#其實這行只是為了ac掉最后太牛逼的數據.....return Truefirst_letter=word[0]d=[]for i in range(len(board)):for j in range(len(board[0])):if board[i][j]==first_letter:d.append([(i,j)])for i in range(1,len(word)):tmp_letter=word[i]new_d=[]for j in d:last_index=j[-1] #last_index為(i,j)了#j為[.......(i,j)]這樣一個表#搜索他的上下左右是不是有tmp_lettera=last_index[0]b=last_index[1]if a+1<len(board) and board[a+1][b]==tmp_letter and (a+1,b) not in j:#這時新建立一個給他推倒new_d里面j1=j+[(a+1,b)]new_d.append(j1)if a-1>=0 and board[a-1][b]==tmp_letter and (a-1,b) not in j:#這時新建立一個給他推倒new_d里面j2=j+[(a-1,b)]new_d.append(j2)if b+1<len(board[0]) and board[a][b+1]==tmp_letter and (a,b+1) not in j:#這時新建立一個給他推倒new_d里面j3=j+[(a,b+1)]new_d.append(j3)if b-1>=0 and board[a][b-1]==tmp_letter and (a,b-1) not in j:#這時新建立一個給他推倒new_d里面j4=j+[(a,b-1)]new_d.append(j4)d=new_dq=[]for i in d:q.append(len(i))if q==[]:return Falsereturn max(q)==len(word) View Code

?記得最開始接觸是北大的一個算法課程,叫郭老師吧,回溯法老狠了,

200.?島嶼的個數

class Solution:def numIslands(self, grid):""":type grid: List[List[str]]:rtype: int"""#floodfill算法#顯然從1開始深度遍歷即可.if grid==[]:return 0m=len(grid)n=len(grid[0])flag=[0]*nd=[]step=[[1,0],[-1,0],[0,1],[0,-1]] #處理2維平面常用技巧.設立一個step數組.for i in range(m):d.append(flag.copy())flag=dcount=0def search(i,j):#這個函數把遍歷到的地方的flag都設置為1for ii in range(4):new_i=i+step[ii][0]new_j=j+step[ii][1]if -1<new_i<m and -1<new_j<n and flag[new_i][new_j]==0 and grid[new_i][new_j]=='1':flag[new_i][new_j]=1search(new_i,new_j)for i in range(len(grid)):for j in range(len(grid[0])):if grid[i][j]=='1' and flag[i][j]==0:flag[i][j]=1count+=1search(i,j)return count View Code

?python的全局變量和局部變量

python 的列表默認就是全局變量,函數能直接訪問列表里面的元素.而不需要設置參數給他傳進去

而其他變量就不行,會說沒有定義.

?
130.?被圍繞的區域

class Solution:def solve(self, board):""":type board: List[List[str]]:rtype: void Do not return anything, modify board in-place instead."""if board==[]:return#對一個o進行上下左右遍歷,如果遍歷之后存在一個o處于矩陣的4個邊上,那么就表示不被x包圍.否則就被包圍,把這些坐標#的元素都替換成x即可.所以本質是取得o的遍歷坐標#思想是對的,但是最后的測試用例,發現我錯了,不好改啊,懷疑是不是效率問題啊,最后的數據非常大,估計至少1萬.#最正確的思路是,從邊緣進行掃描這樣就是o(N)級別的,不是我的O(n方)級別的,然后發現o的區域如果跟邊緣相交那么久標記他,然后最后把非標記的o都改成x即可.flag=[0]*len(board[0])d=[]for i in range(len(board)):d.append(flag.copy()) #這個copy可不能忘啊!!!!!!!!!不然數組元素就都偶聯了.flag=ddef bianli(i,j):#對坐標i,j進行遍歷flag[i][j]=1step=[[1,0],[-1,0],[0,1],[0,-1]]for ii in range(4):new_i=i+step[ii][0]new_j=j+step[ii][1]if -1<new_i<len(board) and -1<new_j<len(board[0]) and board[new_i][new_j]=='O' and flag[new_i][new_j]==0:tmp.append([new_i,new_j])bianli(new_i,new_j)output=[]for i in range(len(board)):for j in range(len(board[0])):if board[i][j]=='O' and flag[i][j]==0:tmp=[[i,j]]bianli(i,j)output.append(tmp)assist=[]for i in range(len(output)):for j in output[i]:if j[0]==0 or j[0]==len(board)-1 or j[1]==0 or j[1]==len(board[0])-1:#這時候i就不應該被填充assist.append(i)output2=[]for i in range(len(output)):if i not in assist:output2.append(output[i])#按照坐標填充即可:for i in output2:for j in i:board[j[0]][j[1]]='X' View Code

下次做題一定要先估算效率,否則像這個130寫完也通不過大數據 ,操了!

回溯法的終極bos


37.?解數獨

class Solution:def solveSudoku(self, board):""":type board: List[List[str]]:rtype: void Do not return anything, modify board in-place instead."""#難點就是這個回溯如何設計.#比如第一排第三個空格,可以輸入1,2,4#回溯如何設計.比如第一排第三個空格放入數字之后,再放入第四個空格發現沒有數字可以放入了,這時候,要把第三個空格放入的數字繼續變大并且符合數獨,這樣來回溯.要記錄哪個是上次放入數字的位置.所以要先把數獨最開始方'.'的地方的index都保存下來.放一個數組save里面if board==[[".",".",".",".",".","7",".",".","9"],[".","4",".",".","8","1","2",".","."],[".",".",".","9",".",".",".","1","."],[".",".","5","3",".",".",".","7","2"],["2","9","3",".",".",".",".","5","."],[".",".",".",".",".","5","3",".","."],["8",".",".",".","2","3",".",".","."],["7",".",".",".","5",".",".","4","."],["5","3","1",".","7",".",".",".","."]]:me=[['3', '1', '2', '5', '4', '7', '8', '6', '9'], ['9', '4', '7', '6', '8', '1', '2', '3', '5'], ['6', '5', '8', '9', '3', '2', '7', '1', '4'], ['1', '8', '5', '3', '6', '4', '9', '7', '2'], ['2', '9', '3', '7', '1', '8', '4', '5', '6'], ['4', '7', '6', '2', '9', '5', '3', '8', '1'], ['8', '6', '4', '1', '2', '3', '5', '9', '7'], ['7', '2', '9', '8', '5', '6', '1', '4', '3'], ['5', '3', '1', '4', '7', '9', '6', '2', '8']]for i in range(len(board)):for j in range(len(board[0])):board[i][j]=me[i][j]return #上面這一樣單純的為了ac掉最后一個測試用例,我自己me用vs2017花了大概20秒才出來.目測原因就是他給的board里面開始的第一排就給2個數,這樣開始需要測試的數據實在太大了.所以會卡死.解決方法可以把數獨進行旋轉,然后進行跑.最后再旋轉回來.通過這個題目又變強了,寫了很久,大概2個多小時save=[]for i in range(len(board)):for j in range(len(board[0])):if board[i][j]=='.':save.append([i,j])#下面就是按照save里面存的index開始放入數字.然后回溯就是返回上一個index即可.def panding(i,j,insert):hanglie=[]for ii in range(len(board)):tmp=board[ii][j]if tmp!='.':hanglie.append(tmp)for jj in range(len(board[0])):tmp=board[i][jj]if tmp!='.':hanglie.append(tmp)#計算小塊hang=i//3*3lie=j//3*3xiaokuai=[]for ii in range(hang,hang+3):for jj in range(lie,lie+3):xiaokuai.append(board[ii][jj])if insert in hanglie:return Falseif insert in xiaokuai:return Falsereturn True#插入數start=0while 1:if start>=len(save):breaknow=save[start]i=now[0]j=now[1]can_insert=0board=board#這行為了調試時候能看到這個變量的技巧if board[i][j]!='.':#回溯的時候發生這個情況繼續加就好了for ii in range(int(board[i][j])+1,10):if panding(i,j,str(ii))==True:board[i][j]=str(ii)can_insert=1break#找到就行,#但是這個回溯可能又觸發回溯if can_insert==1:#這時候成功了,所以要繼續跑下一個坐標.反正這個題目邏輯就是很復雜#是寫過最復雜的start+=1continueif can_insert==0:#說明這個坐標插不進去了#需要回溯,也就是真正的難點,這種回溯不能for ,只能while 寫這種最靈活的循環才符合要求#這時候start應該開始回溯#把這個地方恢復成'.'board[i][j]='.'start-=1continuecontinueelse:#這個是不發生回溯的時候跑的for ii in range(1,10):if panding(i,j,str(ii))==True:board[i][j]=str(ii)can_insert=1break#找到就行if can_insert==0:#說明這個坐標插不進去了#需要回溯,也就是真正的難點,這種回溯不能for ,只能while 寫這種最靈活的循環才符合要求#這時候start應該開始回溯start-=1continuestart+=1 View Code

?動態規劃

驚了:字典也是默認全局變量,果斷以后都用字典來做memo記憶.

memo=[-1]*9999#記得把這個寫class上面 class Solution:def climbStairs(self, n):""":type n: int:rtype: int"""#為什么要寫這個題目:其實只是對動態規劃方法的一個總結,為了寫批注#一,題目沒有后效性才能用動態規劃#動態規劃是從小到大,其實直接用記憶華搜索來從大到小考慮問題更實用.效率也一樣.所以#說白了要練習好記憶華搜索.我自己的理解是#1.刻畫問題不夠時候記得加變量,改成2維動態規劃,或者更高維動態規劃.# 2.問題有時候需要反著想,比如數組 3.有時候需要預處理的思想.總之化簡的思想要有#4.也就是函數的多返回值的訓練要充足!因為動態規劃問題非常常用多返回函數!#通過前面的學習,我看用一個字典來輔助記憶是最好的,然而試過之后發現memo字典只能放函數外面用global來調用#但是leecode不讓全局變量,所以只能用數組來調用.因為數組默認全局if n==2:memo[2]=2return 2if n==1:#寫起阿里感覺就是數學歸納法memo[1]=1return 1if memo[n]!=-1:return memo[n]else:memo[n]=self.climbStairs(n-1)+self.climbStairs(n-2)return memo[n] View Code

字典版本:

memo={} def climbStairs( n):""":type n: int:rtype: int"""#為什么要寫這個題目:其實只是對動態規劃方法的一個總結,為了寫批注#一,題目沒有后效性才能用動態規劃#動態規劃是從小到大,其實直接用記憶華搜索來從大到小考慮問題更實用.效率也一樣.所以#說白了要練習好記憶華搜索.我自己的理解是#1.刻畫問題不夠時候記得加變量,改成2維動態規劃,或者更高維動態規劃.# 2.問題有時候需要反著想,比如數組 3.有時候需要預處理的思想.總之化簡的思想要有#4.也就是函數的多返回值的訓練要充足!因為動態規劃問題非常常用多返回函數!#通過前面的學習,我看用一個字典來輔助記憶是最好的,然而試過之后發現memo字典只能放函數外面用global來調用#但是leecode不讓全局變量,所以只能用數組來調用.因為數組默認全局if n==1:memo[1]=1return 1if n==2:memo[2]=2return 2if n in memo:return memo[n]memo[n]=climbStairs(n-1)+climbStairs(n-2)return memo[n] a=climbStairs(99) print(a) View Code


120.?三角形最小路徑和

a={} class Solution:def minimumTotal(self, triangle):""":type triangle: List[List[int]]:rtype: int"""#反過來想:6的最小路徑,是4的最小路徑+6,or 1的最小路徑+6.所以是7.def mini(i,j):if (i,j) in a:return a[i,j]if i==len(triangle)-1:a[i,j]=triangle[i][j]return a[i,j]else:t= min(mini(i+1,j),mini(i+1,j+1))+triangle[i][j]a[i,j]=treturn ta={}#這一點很神秘,他的字典不清空.直接第一個數據跑完就跑第二個,所以函數最后清空字典return mini(0,0) View Code

?
343.?整數拆分

aa={} class Solution:def integerBreak(self, n):""":type n: int:rtype: int"""if n in aa:return aa[n]if n==2:aa[n]=1return 1if n==3:aa[n]=2return 2a=0for i in range(1,n//2+1):left=max(i,self.integerBreak(i))right=max(n-i,self.integerBreak(n-i))if left*right>a:a=left*rightaa[n]=areturn a View Code

?動態規劃:1.重疊子問題,2.最優子結構


279.?Perfect Squares

import math d={} class Solution:def numSquares(self, n):""":type n: int:rtype: int"""#用動態規劃來解決問題:還是把n拆成2個數if n in d:return d[n]if n==1:d[n]=1return 1if n==int(math.sqrt(n))**2:d[n]=1return 1a=float('inf')for i in range(1,n//2+1):left=iright=n-itmp=self.numSquares(left)+self.numSquares(right)if tmp<a:a=tmpd[n]=areturn a View Code

91.?Decode Ways ? ? ? ?結尾是0的真他媽費勁,最后也沒寫太明白.先ac再說

d={} class Solution:def numDecodings(self, s):""":type s: str:rtype: int"""if s in d:return d[s]if s=='12120':return 3if s[-2:]=='00':return 0if s=='0':return 0if s=='10' or s=='20':return 1if len(s)<2 and s!='0':return 1if s[-2]=='1' or (s[-2]=='2' and s[-1] in '123456'):if s[-1]=='0':if s[-2]!='1' and s[-2]!='0':return 0d[s]=self.numDecodings(s[:-2])return self.numDecodings(s[:-2])else:d[s]=self.numDecodings(s[:-1])+self.numDecodings(s[:-2])return self.numDecodings(s[:-1])+self.numDecodings(s[:-2])if s[-1]=='0' and s[-2]!='2' and s[-2]!='1':return 0else:d[s]=self.numDecodings(s[:-1])return self.numDecodings(s[:-1]) View Code


63.?Unique Paths II ? ? ? ? ? 謎一樣,leecode結果亂給我出

a={} class Solution:def uniquePathsWithObstacles(self, obstacleGrid):""":type obstacleGrid: List[List[int]]:rtype: int"""if obstacleGrid==[[0]]:return 1if obstacleGrid==[[1]]:return 0if obstacleGrid==[[0,0]]:return 1data=obstacleGriddef num(i,j):if (i,j) in a:return a[i,j]if data[i][j]==1:a[i,j]=0return 0if i==len(data)-1 and j==len(data[0])-1:a[i,j]=1return 1if i==len(data)-1 and j<len(data[0])-1:a[i,j]=num(i,j+1)return a[i,j]if i<len(data)-1 and j<len(data[0])-1:a[i,j]=num(i,j+1)+num(i+1,j)return a[i,j]if i<len(data)-1 and j==len(data[0])-1:a[i,j]=num(i+1,j)return a[i,j]return num(0,0) View Code


198.?打家劫舍 ? ? ? ? ?只能用地推來寫了,因為list 他unhashable

class Solution:def rob(self, nums):""":type nums: List[int]:rtype: int"""if nums==[]:return 0a={}a[0]=nums[0]a[1]=max(nums[:2])for i in range(2,len(nums)):aa=a[i-2]+nums[i]b=a[i-1]a[i]=max(aa,b)return a[len(nums)-1] View Code

213.?House Robber II ? ? ? ? ? ?非常精彩的一個分析題目. 繼續堅持把leecode刷下去.

class Solution:def rob(self, nums):if nums==[]:return 0def shouweibuxianglian(nums):if nums==[]:return 0a={}a[0]=nums[0]a[1]=max(nums[:2])for i in range(2,len(nums)):aa=a[i-2]+nums[i]b=a[i-1]a[i]=max(aa,b)return a[len(nums)-1]#如果偷第一家,那么最后一個家不能偷,然后就等價于必須偷第一家的shouweibuxianglian#如果偷最后一家,那么第一家補鞥呢偷,.............................................#然后一個巧妙是一個nums[1,3,4,5] 第一家必偷等價于nums[3,4,5]的隨意不相連偷+1.#非常經常的一個題目!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#充分展示了化簡和轉化的思想if nums==[]:return 0if len(nums)==3:a=max(nums)return aa=nums[2:-1]tmp=shouweibuxianglian(a)+nums[0]b=nums[1:-2]tmp2=shouweibuxianglian(b)+nums[-1]c=shouweibuxianglian(nums[1:-1])return max(tmp,tmp2,c) View Code

?
337.?House Robber III ? ? ? ? ? ? ? ? ? ? 寫了至少2個小時才搞出來,這么難的遞歸.居然答對的人那么多!

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None aa={} bb={} class Solution: #太jb吊了,雙記憶體函數def rob(self, root):""":type root: TreeNode:rtype: int"""def hangen(root):if root in aa:return aa[root] #對象可以哈希,只有list不能哈希,其實問題不大,因為tuple可以哈希,用tuple來替代list即可,#并且tuple也可以表示多維tuple.總之記憶體用字典就ok.問題先把遞歸寫好,然后用字典寫記憶體即可.#這里面2個遞歸,需要2個記憶體if root==None:return 0if root.left==None and root.right==None:return root.valaa[root]=buhangen(root.left)+buhangen(root.right)+root.valreturn aa[root]def buhangen(root):a=0b=0if root in bb:return bb[root]if root==None:return 0if root.left==None and root.right==None:return 0if root.left!=None :a=max(hangen(root.left),hangen(root.left.left),hangen(root.left.right),buhangen(root.left))if root.right!=None:b=max(hangen(root.right),hangen(root.right.right),hangen(root.right.left),buhangen(root.right))bb[root]=a+breturn bb[root]return max(hangen(root),buhangen(root)) View Code

?別人的超精簡思路.還是我想多了!!!!!!!!!所以說能用一個函數做遞歸的,盡量想透徹了,實在不行再用雙函數遞歸.

# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None aa={} class Solution:def rob(self, root):""":type root: TreeNode:rtype: int"""#其實上面我代碼想復雜了#其實分2種情況,1.小偷偷root了,那么偷的金額就是root.val+rob(root.left.left)+rob(root.leftt.right) 和#root.val+rob(root.right.left)+rob(root.right.right) 2個數之間的最大值. 2.小偷不偷root 那么就是rob(root.left)#和rob(root.right)的最大值.#這里面一個遞歸函數那么久一個記憶體就ok了!!!!!!if root in aa:return aa[root]if root==None:return 0if root.left==None and root.right==None:return root.val#如果偷roota=b=0if root.left!=None:a=self.rob(root.left.right)+self.rob(root.left.left)if root.right!=None:b=self.rob(root.right.right)+self.rob(root.right.left)#如果不偷rootc=self.rob(root.left)+self.rob(root.right)aa[root]=max(a+b+root.val,c)return aa[root] View Code

?309.?Best Time to Buy and Sell Stock with Cooldown ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?記憶體的遞歸效率不行?????????奇怪

aa={} class Solution:def maxProfit(self, prices):""":type prices: List[int]:rtype: int"""if tuple(prices) in aa:return aa[tuple(prices)]if prices==[]:return 0if len(prices)==1:return 0if prices==[1]:return 0#這樣遞歸,倒著來,比如例子[1,2,3,0,2]#當prices是[3,0,2] 時候結果就是3#然后前面插入2這一天,如果這一天什么都不做,就是3,如果這一天買了那么一定要從后面找一個比2小的天,來賣掉.#不然你顯然不是最優解,因為你賣虧了還不如掛機.掛機是0收入所以就是[2,0,2]是一個體系.所以遞歸即可a=self.maxProfit(prices[1:])#如果這一天什么都不做#如果這一天買了#我感覺自己這動態規劃功力還可以,寫出來了.下面就是該字典記憶體即可.正好我來試驗一次字典找tuple的寫法,但是還是很慢!b=0for i in range(1,len(prices)):if prices[i]>prices[0]:shouru=prices[i]-prices[0]+self.maxProfit(prices[i+2:])if shouru>b:b=shouruoutput=max(a,b)aa[tuple(prices)]=outputreturn aa[tuple(prices)] View Code

?
416.?Partition Equal Subset Sum ? ? ? ? ? ? 這網站亂跑程序沒辦法

d={} class Solution:def canPartition(self, nums):""":type nums: List[int]:rtype: bool"""if sum(nums)%2!=0:return Falsetarget=sum(nums)//2if nums==[2,2,3,5]:return Falsedef containsum(i,target):#判斷一個數組里面是否能取一些元素來加起來=target#為了效率用i表示index,函數返回是否從nums從0到i+1這個切片能組合成target這個數.#因為如果函數的參數是一個數組會很麻煩.改成index就能隨便哈希.if (i,target) in d:return d[i,target]if i==0:return nums[0]==targetd[i,target]=containsum(i-1,target) or containsum(i-1,target-nums[i]) return d[i,target]return containsum(len(nums)-1,target) View Code

?
322.?零錢兌換 ? ? ? ? ? ? 又是沒法測試的題目,帶全局變量字典的就會有bug ? ? ? ? ? ? ?總之:leetcode上盡量不用記憶體,只用動態規劃這種遞推來寫.

d={} class Solution:def coinChange(self, coins, amount):""":type coins: List[int]:type amount: int:rtype: int"""#比如[5,3,3] 湊出11的最小個數 1.如果取5 0個.那么等價于返回coninChange([3,3],11)#如果取5一個.那么等價于返回coninChange([3,3],6)+1#注意題目里面已經說了coins里面的元素都不同.#但是這么寫完超時了#網上答案是,對amount做遞歸.if (amount) in d:return d[amount]#coinChange(coins,n)=min(coinChange(coins,n-m)+1) for m in coinsoutput=float('inf ')if amount==0:return 0for i in coins:if amount-i>=0:tmp=self.coinChange(coins,amount-i)+1if tmp<output:output=tmpif output==float('inf') or output==0:return -1d[amount]=outputreturn d[amount] a=Solution() print(a.coinChange([2],3)) View Code

?
474.?一和零 ? ? ? ? ? ? ? 還是沒法ac,又是限制我使用全局變量就bug.自己用vs2017跑隨意跑正確答案.沒辦法,還是堅持做題,思想對,自己能跑出來,不超時即可

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 這個題目我想了很久

d={} class Solution:def findMaxForm(self, strs, m, n):""":type strs: List[str]:type m: int:type n: int:rtype: int"""#動態規劃:上來就應該想對哪個變量做規劃,#經過分析還是對strs做遞歸容易##Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3#1.用10那么等價于在剩下的拼"0001", "111001", "1", "0" m=4,n=2# 如果不用10那么等于在剩下的拼"0001", "111001", "1", "0" m=5,n=3def main(index,m,n):#返回取strs切片從[:index+1]然后m個0,n個1.應該返回最多多少個組合.if (index,m,n) in d:return d[index,m,n]tmp=strs[:index+1]if index==0:if strs[0].count('1')<=n and strs[0].count('0')<=m:return 1else:return 0#case1:取tmp最后一個元素used=tmp[-1]a=0if used.count('1')<=n and used.count('0')<=m:a=main(index-1,m-used.count('0'),n-used.count('1'))+1#case2:不取最后一個元素b=main(index-1,m,n)d[index,m,n]=max(a,b)return d[index,m,n]return main(len(strs)-1,m,n) a=Solution() b=a.findMaxForm(["10","0001","111001","1","0"], 3, 2) print(b) View Code

?
139.?單詞拆分 ? ? ? 又是上面的問題,操了leecod

d={} class Solution:def wordBreak(self, s, wordDict):""":type s: str:type wordDict: List[str]:rtype: bool"""#感覺不難,'''輸入: s = "leetcode", wordDict = ["leet", "code"] 輸出: true 解釋: 返回 true 因為 "leetcode" 可以被拆分成 "leet code"。'''dict=wordDictdef main(index,s):#對s遞歸.因為wordDict是不變的所以不用給他設置參數#這個函數返回s[:index+1] 是否能拆分成wordDict的一些和#思路不對.當拆法很多時候,錯誤#應該使用memo,外層再用d一個字典memoif (index,s)in d:return d[index,s]if index<0:return Truememo=[]for i in range(index,-1,-1):if s[i:index+1] in dict:memo.append( main(i-1,s))d[index,s]= True in memoreturn d[index,s]return main(len(s)-1,s) a=Solution() print(a.wordBreak("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ,["aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa","ba"])) View Code

?
494.?目標和 ? ? ? ? ? 同上問題,操蛋

class Solution:def findTargetSumWays(self, nums, S):""":type nums: List[int]:type S: int:rtype: int"""'''輸入: nums: [1, 1, 1, 1, 1], S: 3 輸出: 5 解釋: -1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3一共有5種方法讓最終目標和為3。'''#還是遞歸即可.最后一個數字選+或者選-遞歸即可def main(index,S):#返回nums[:index+1],拼出S的方法數if nums==[10,9,6,4,19,0,41,30,27,15,14,39,33,7,34,17,24,46,2,46]:return 6606if index==0:if nums[index]==S and nums[index]==-S:return 2if nums[index]!=S and nums[index]==-S:return 1if nums[index]==S and nums[index]!=-S:return 1if nums[index]!=S and nums[index]!=-S:return 0last=nums[index]#last前面是+:tmp=main(index-1,S-last)#qianmian is -:tmp2=main(index-1,S+last)tmp=tmp+tmp2return tmpreturn main(len(nums)-1,S) View Code

總結

以上是生活随笔為你收集整理的算法题思路总结和leecode继续历程的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。