class Solution(object): def generateParenthesis(self, n): res = [] self.dfs(res, n, n, '') return res def dfs(self, res, left, right, tmp): if left == 0 and right == 0: res.append(tmp) return if left > 0: self.dfs(res, left - 1, right, tmp + '(') if left < right: self.dfs(res, left, right - 1, tmp + ')')
defreverseWords1(s): whileTrue: # 去除头空格 if len(s) == 0: return"" if s[0] == ' ': s = s[1:] continue else: break p,q = 0,1 length = len(s) word = '' words = [] whileTrue: ##当指针到达字符串末尾时,结束循环,并将最后一个单词加入,如果是空白字符串,就不加入 if q == length - 1: if s[p] != ' ' : word = word + s[p] if s[q] != ' ': word = word + s[q] if word == ''or word == ' ': break
words.append(word) break
if q > length - 1: if s[p] != ' ': word = word + s[p] if word == ""or word == ' ': break words.append(word) break
if s[p] != ' 'and s[q] != ' ': word = word + s[p] word = word + s[q] p = p + 2 q = q + 2
elif s[p] != ' 'and s[q] == ' ': word = word + s[p] words.append(word) word = '' p = p + 2 q = q + 2 elif s[p] == ' 'and s[q] != ' ':
words.append(word) word = '' p = p + 1 q = q + 1 elif s[p] == ' 'and s[q] == ' ':
p = p + 2 q = q + 2
length = len(words) - 1 s = '' while length > -1: if words[length] == '': length = length - 1 continue s = s + words[length] + ' ' length = length - 1
defthrowEgg(K,N): #若楼高K为1,则一次 if K == 1: return1 #创建 K+1 行 N+1列的数组(注意这里生成数组 不能使用[[0] * (N + 1)]*(K + 1) #因为这样生成的数组,只是生成了k+1个引用,当修改值时会一起修改从而导致bug res = [[0] * (N + 1) for _ in range(K + 1)] #如果 只有一个鸡蛋,那么次数就为楼高 for i in range(1,N+1): res[1][i] = 1 m = -1 #遍历所有楼层的情况 for i in range(2,K+1): #在指定楼层,遍历所有鸡蛋的情况,这里是通过最基本的情况,去求解复杂的情况 for j in range(1, N + 1): res[i][j] = 1 + res[i - 1][j - 1] + res[i - 1][j] if res[i][N] >= K: m = i break return m
defgetNewsFeed(self, userId: int): """ Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. """ if userId in self.content: mycontent = copy.deepcopy(self.content[userId]) else: mycontent = [] if userId in self.star: followees = copy.deepcopy(self.star[userId]) else: followees = [] fcontent = [] res = [] tweetId = 0 if followees : for id in followees: #判断用户是否发过twitter if id in self.content: fcontent.extend(self.content[id])
mycontent.extend(fcontent) #print("mycontent",mycontent) i=0 while i <= 9: min = float('-inf') if mycontent: for val in mycontent: #print(val) tmp = val.split('-') posttime = float(tmp[1]) if posttime > min: tweetId = tmp[0] min = posttime if tweetId notin res: res.append(tweetId) i = i + 1
mycontent.remove(str(tweetId) + '-' + str(min))
else: break return res else: for i in range(10): if mycontent: id = mycontent.pop().split('-')[0] if id notin res: res.append(id) else: break return res
deffollow(self, followerId: int, followeeId: int) -> None: """ Follower follows a followee. If the operation is invalid, it should be a no-op. """ if followerId notin self.star: self.star[followerId] = [] self.star[followerId].append(followeeId) else: self.star[followerId].append(followeeId)
defunfollow(self, followerId: int, followeeId: int) -> None: """ Follower unfollows a followee. If the operation is invalid, it should be a no-op. """ if followerId in self.star: if followeeId in self.star[followerId]: self.star[followerId].remove(followeeId)
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defaddTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: arr1 = [] arr2 = [] f1 = f2 = True while f1: arr1.append(l1.val) if l1.next != None: l1 = l1.next else: f1 = False while f2: arr2.append(l2.val) if l2.next != None: l2 = l2.next else: f2 = False res = [] if len(arr1) >= len(arr2): big = arr1 small = arr2 else: big = arr2 small = arr1 #b为进位数 b = 0 while small != []: result = big.pop() + small.pop() + b if result >= 10: res.insert(0,result-10) b = 1 else: res.insert(0,result) b = 0
while big != []: result = big.pop() + b if result >= 10 : res.insert(0,result-10) b = 1 else: res.insert(0,result) b = 0
if big == [] and b == 1: res.insert(0,b)
cache = None for i in res: tmp = ListNode(i) if cache != None: cache.next = tmp cache = tmp else: head = ListNode(i) cache = head return head
classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: i = 0 length = len(nums) while i < length - 1: sub = target - nums[i] if sub in nums[i + 1:]: return (i,i + nums[i + 1:].index(sub)+1) i += 1
classSolution: defcanJump(self, nums: List[int]) -> bool: n, rightmost = len(nums), 0 for i in range(n): if i <= rightmost: rightmost = max(rightmost, i + nums[i]) if rightmost >= n - 1: returnTrue returnFalse
defreversestr(x): s='' for tmp in str(x): s = tmp + s x = int(s) if x < -2**31or x > 2**31-1: return0 else: return x classSolution: defreverse(self, x: int) -> int: if x == 0: return0 elif x < 0: x = -x return -reversestr(x) else: return reversestr(x)
def__init__(self): """ initialize your data structure here. """ self.s = [] self.min = float('inf')
defpush(self, x: int) -> None: self.s.append(x) if x < self.min: self.min = x
defpop(self) -> None: if self.s: self.s.pop()
deftop(self) -> int: if self.s: return self.s[-1]
defgetMin(self) -> int: if self.s: return min(self.s)
# Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(x) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin()
classSolution: defsingleNumber(self, nums: List[int]) -> int: map = {} for i in nums: if i notin map: map[i] = 0 else: map[i] += 1 for k,v in map.items(): if v == 0: return k
classSolution: kuohao = { ')':'(', ']':'[', '}':'{' } defisValid(self, s: str) -> bool: stack = [] if len(s) <= 1: returnFalse for i in s : if i == '('or i =='['or i == '{': stack.append(i) else: if len(stack) == 0: returnFalse left = stack.pop() if self.kuohao[i] != left: returnFalse if len(stack) == 0: returnTrue else: returnFalse
I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。 X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。 给定一个整数,将其转为罗马数字。输入确保在 1 到 3999 的范围内。
classSolution: defintToRoman(self, num: int) -> str: res = '' q = num // 1000 if q > 0: num -= q * 1000 for x in range(q): res += 'M'
b = num // 100 if b == 9 : num -= 900 res += 'CM' elif b >= 5: num -= b * 100 res += 'D' for x in range(b-5): res += 'C' elif b == 4: num -= 400 res += 'CD' elif b > 0 : num -= b * 100 for x in range(b): res += 'C'
s = num // 10 if s == 9 : num -= 90 res += 'XC' elif s >= 5: num -= s * 10 res += 'L' for x in range(s-5): res += 'X' elif s == 4: num -= 40 res += 'XL' elif s > 0 : num -= s * 10 for x in range(s): res += 'X' if num == 9: res += 'IX' elif num >= 5: res += 'V' for x in range(num-5): res += 'I' elif num == 4: res += 'IV' elif num > 0: for x in range(num): res += 'I' return res
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defreverseList(self, head: ListNode) -> ListNode: h = None while head isnotNone: temp = ListNode() temp.val = head.val temp.next = h h = temp head = head.next return h
classSolution: map = { "I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000,"IX":9 } defromanToInt(self, s: str) -> int: res = i = 0 l = len(s) while i + 1 < l: if self.map[s[i]] < self.map[s[i+1]]: res -= self.map[s[i]] res += self.map[s[i+1]] i += 2 else: res += self.map[s[i]] i += 1 if i == l - 1: res += self.map[s[l-1]] return res
def__init__(self): """ Initialize your data structure here. """ self.map = [] self.key = {}
defaddWord(self, word: str) -> None: if word notin self.key: self.map.append(word) self.key[word] = True
defsearch(self, word: str) -> bool: if word in self.key: returnTrue length = len(word) for val in self.map: if length != len(val): continue i = 0 while i < length: if word[i] == val[i] or word[i] == '.': i += 1 else: break if i == length: self.key[word] = True returnTrue returnFalse
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: a = b = c = 0 p = head = ListNode() while l1 or l2: node = ListNode() if l1: a = l1.val l1 = l1.next else: a = 0 if l2 : b = l2.val l2 = l2.next else: b = 0 if a + b + c > 9: node.val = a + b + c - 10 c = 1 else: node.val = a + b + c c = 0 p.next = node p = node if c == 1: p.next = ListNode(1) return head.next 。
classSolution: deffrequencySort(self, s: str) -> str: map = {} for val in s: if val notin map: map[val] = 1 else: map[val] += 1 map = dict(sorted(map.items(),key=lambda x:x[1],reverse=True)) str = '' for key in map: i = 0 length = map[key] while i < length: str += key i += 1 return str
classSolution: defdisplayTable(self, orders: List[List[str]]) -> List[List[str]]: map = {} menu = [] for arr in orders: num = int(arr[1]) menu += arr[2:] if num notin map: map[num] = arr[2:] else: map[num].extend(arr[2:]) key = sorted(map) menu = sorted(set(menu)) res = [] menu.insert(0,'Table') res.append(menu) for num in key: temp = [] temp.append(str(num)) for val in menu[1:]: temp.append(str(map[num].count(val))) res.append(temp) return res
classSolution: deftribonacci(self, n: int) -> int: if n == 0: return0 elif n <= 2: return1 a,b,c,d = 0,1,1,0 for i in range(2,n): d = a + b + c a = b b = c c = d return d
classSolution: defminCostClimbingStairs(self, cost: List[int]) -> int: if len(cost) == 2:return min(cost) a = b = 0 n = len(cost) for i in range(2, n + 1): c = min(b + cost[i - 1], a + cost[i - 2]) a, b = b, c return b
classSolution: defrob(self, nums: List[int]) -> int: n = len(nums) if n == 1:return nums[0] if n == 2:return max(nums) a = nums[0] b = max(nums[0:2]) for i in range(2,n): sum = max(a + nums[i],b) a = b b = sum return b # class Solution: # def rob(self, nums: List[int]) -> int: # n = len(nums) # if n == 1:return nums[0] # if n == 2:return max(nums) # dp = [0] * n # dp[0] = nums[0] # dp[1] = max(nums[0:2]) # for i in range(2,n): # dp[i] = max(dp[i-2] + nums[i],dp[i-1])
classSolution: defrob(self, nums: List[int]) -> int: defrobYou(arr): n = len(arr) a = arr[0] b = max(arr[0:2]) for i in range(2,n): sum = max(a + arr[i],b) a = b b = sum return b n = len(nums) if n == 1:return nums[0] if n == 2:return max(nums) return max(robYou(nums[0:n-1]),robYou(nums[1:]))
classSolution: defdeleteAndEarn(self, nums: List[int]) -> int: n = len(nums) if n == 1: return nums[0] new = [0] * (max(nums) + 1) for i in nums: if new[i] == 0: new[i] = i * nums.count(i) a = new[0] b = max(new[0:2]) for i in range(2,len(new)): sum = max(a + new[i],b) a = b b = sum return b
classSolution: defcanJump(self, nums: List[int]) -> bool: max_distance = 0 n = len(nums) - 1 for i,v in enumerate(nums): if i > max_distance : returnFalse if i + v >= n : returnTrue max_distance = max(max_distance,i + v)
classSolution: defmaxSubArray(self, nums: List[int]) -> int: n = len(nums) if n == 1: return nums[0] p = maxsum = nums[0] for i in range(1,n): p = max(nums[i], p + nums[i]) maxsum = max(p,maxsum) return maxsum
classSolution: defsearch(self, nums: List[int], target: int) -> int: try: i = nums.index(target) except: return0 count = 1 for v in nums[i+1:]: if v == target: count += 1 continue break
classSolution: defmaxValue(self, grid: List[List[int]]) -> int: row, col = len(grid), len(grid[0]) for j in range(1,col): grid[0][j] += grid[0][j-1] for i in range(1,row): grid[i][0] += grid[i-1][0] for i in range(1,row): for j in range(1,col): grid[i][j] += max(grid[i-1][j],grid[i][j-1])