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