738、单调递增的数字:
python
class Solution(object):
def monotoneIncreasingDigits(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 0
nums = [int(i) for i in str(n)]
flag = len(nums)
for i in range(len(nums)-1, 0, -1):
if nums[i] < nums[i-1]:
nums[i-1] -= 1
flag = i
for i in range(len(nums)):
if i >= flag:
nums[i] = 9
return int(''.join([str(i) for i in nums]).lstrip('0'))
选择从前往后遍历还是从后往前遍历是本题的关键,一旦确定了从后往前遍历,注意代码技巧就可以了
968、监控二叉树:
python
class Solution(object):
def __init__(self):
self.res = 0
def traversal(self, cur):
if not cur:
return 2
left = self.traversal(cur.left)
right = self.traversal(cur.right)
if left == 2 and right == 2:
return 0
if left == 0 or right == 0:
self.res += 1
return 1
if left == 1 or right == 1:
return 2
return -1
def minCameraCover(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if self.traversal(root) == 0:
self.res += 1
return self.res
本题是贪心算法和二叉树的结合,需要约定好不同情形下左右子树传回的值,来确定当前节点的状态,从而判断监控的数量