interviewer:
Image Not Showing Possible ReasonsLearn More →
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
interviewee:Image Not Showing Possible ReasonsLearn More →
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
給定一棵二元樹,檢查它是否是其自身的鏡像(即圍繞其中心對稱)。
已知樹節點資料結構如下:
最快想到的方法就是用遞迴解決,因為程式碼可讀性高,而且相對容易撰寫。
首先確定根節點是否存在,接著透過遞迴持續比對將所有子節點,直到走訪所有節點。
比對方法左右子樹節點是否一有一無,或者是值不相同。
比對時需注意“左子樹右節點”是和“右子樹左節點”比對,以此類推。
優點:可讀性高,容易撰寫和維護。
缺點:當在binary tree很大時,運行遞迴需維護的stack可能會無法負荷。
時間複雜度最差就是O(n),因為必須要比完所有的節點才知道是否對稱。
不用遞迴的話,就要自己透過一些資料結構來紀錄節點資訊了。
我選擇用兩個queue來紀錄兩邊的節點,並加以比對。
需注意的是while loop的結束條件是queue為空,與遞迴時不一樣,當子節點皆為nullptr時還是需要繼續比對,因為有可能是左子樹的左子點為空但右子點不同的情形
時間複雜度一樣最差就是O(n),因為必須要比完所有的節點才知道是否對稱。
給定一組不重複的候選數字 (candidates)和一個目標數(target),請找出候選數字中加總和達到目標數的所有組合。
其中可以從候選數字中無限次地選擇同個數字。
所有數字(包括目標數)都是正整數。
用遞迴做深度優先搜尋如上圖,使用cur來紀錄每次搜尋過程,一但符合target,就存到ans中。
而在此之前,可以先排序候選數字 (candidates),這樣搜尋過程中遇到候選數字 (candidates)大於target的情況,就能確保後面的數字都大於target,不用再繼續找下去。且遞迴也可以從最小開始找起。如此一來就能找出所有可能組合解。
Imagine you're climbing a staircase with 'n' steps, and you can either climb 1 step or 2 steps at a time. how many different ways can you reach the top?
This recursive function will make two recursive calls for each input 'n' except for the base cases when 'n' is 1 or 2.
Therefore, the number of recursive calls grows exponentially with 'n' because each call branches into two more calls.
So The time complexity can be expressed as O(), where 'n' is the input size (number of steps).
This is a fairly high time complexity and will lead to very high computational costs when the number of stairs is large.
This algorithm uses a for loop to iterate through 'n' steps to calculate the number of ways to reach each step.
In the loop, it performs constant-time operations for each step.
Therefore, the time complexity of this dynamic programming solution is O(n), where 'n' is the input size (number of steps).
&
是講專業術語不是and。