練習寫過題目的一天~
就算是寫過的題目,過了一陣子還是會有不同的寫法,甚至有些根本忘了怎麼寫
為了不重複貼文,這邊只寫新寫的題目
The Tribonacci sequence Tn is defined as follows:
T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.
Given n, return the value of Tn.
費氏數列是前兩項,這題變前三項,所以寫起來其實感覺一樣。
這邊第一個寫正常解,後面補一個其實我覺得也是正常解啦.....。
class Solution:
#費氏數列進階款
def tribonacci(self, n: int) -> int:
a,b,c,ans = 0,1,1,0
if n == 0:
return 0
elif n <= 2:
return 1
while n >= 3:
ans = a + b + c
a,b,c = b,c,ans
n -= 1
return ans
#n又不大我直接讀表啦,爽(我不做人啦JOJO)
def tribonacci(self, n: int) -> int:
nList = [0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136, 5768, 10609, 19513, 35890, 66012, 121415, 223317, 410744, 755476, 1389537, 2555757, 4700770, 8646064, 15902591, 29249425, 53798080, 98950096, 181997601, 334745777, 615693474, 1132436852, 2082876103]
return nList[n]
就讀完整的BST,把low~high之間的數字全部加起來。
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
#找出所有在low跟high範圍內的數字加起來
#這是BST所以可以有一些「排富條款」
#沒有排富條款
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
def dfs(root):
if root is None:
return 0
temp = root.val if low<=root.val<=high else 0
return dfs(root.left) + dfs(root.right) + temp
return dfs(root)
class Solution:
#找出所有在low跟high範圍內的數字加起來
#這是BST所以可以有一些「排富條款」
#有排富條款
#左邊的child無論數字再大,都不會比他的祖父節點大:
#似乎不需要,看其他人都沒這樣寫
#右邊剛好相反
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
def dfs(root):
if root is None:
return 0
if root.val < low:
return dfs(root.right)
elif root.val > high:
return dfs(root.left)
temp = root.val if low<=root.val<=high else 0
return dfs(root.left) + dfs(root.right) + temp
return dfs(root)
There is a special keyboard with all keys in a single row.
Given a string keyboard of length 26 indicating the layout of the keyboard (indexed from 0 to 25). Initially, your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from index i to index j is |i - j|.
You want to type a string word. Write a function to calculate how much time it takes to type it with one finger.
class Solution:
#會有一個串列叫做keyword儲存全部的字母
#要把word裡所有的字母的索引值找出來,然後計算現在這一個跟下個字母的距離
def calculateTime(self, keyboard: str, word: str) -> int:
keyDict = {keyboard[i]:i for i in range(26)}
ans = temp = keyDict[word[0]]
for i in word[1:]:
ans = ans + abs(keyDict[i] - temp) #忘記是算距離,沒有加abs絕對錯
temp = keyDict[i]
return ans
以上就是今天的練習感謝大家