代码随想录算法训练营第三十七天| 738.单调递增的数字,968.监控二叉树
738.单调递增的数字
题目链接:单调递增的数字
这个题的贪心思路是,从个位往前看,如果i位的数字小于(i+1)位,那么就直接让i位和i位之前的数都变成9,这样就可以保证是最大的单调递增数字。
class Solution:
def monotoneIncreasingDigits(self, n: int) -> int:
s = str(n)
s = list(s[::-1])
#print(s)
if len(s) == 1: return n
for i in range(len(s)-1):
if int(s[i]) < int(s[i+1]):
s[:(i+1)] = ['9']*(i+1)
s[i+1] = str(int(s[i+1])-1)
if s[-1] == '0':
s.pop()
s = ''.join(s)
s = s[::-1]
return int(s)
968.监控二叉树
题目链接:监控二叉树
写了一个不大好的版本但勉强能过。
我写的是楼下没监控的自己就放一个,楼下有监控的自己就写被覆盖,但有一个情况就是楼下被覆盖了怎么办,一般来说为了少放监控就不管,然后去楼上放一个,但是有一种情况就是,没有楼上了,已经在root了,所以我有加了一个如果root没有被覆盖,那就自动加上一个监控,感觉有点不严谨,但是也能走,二刷的时候试一下有输出的traversal 吧。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minCameraCover(self, root: Optional[TreeNode]) -> int:
res = 0
def traversal(root):
nonlocal res
if not root:
return
traversal(root.left)
traversal(root.right)
if ((root.right) and (root.right.val==0)) or ((root.left) and (root.left.val==0)):
res += 1
root.val = 1
if root.right:
root.right.val = 2
if root.left:
root.left.val = 2
if ((root.right) and (root.right.val==1)) or ((root.left) and (root.left.val==1)):
root.val = 2
result.append(root.val)
if (not root.left) and (not root.right):
return 1
result = []
traversal(root)
if result[-1] == 0 and (result[-2] != 1):
res += 1
return res
return res