lc780. Reaching Points

371 阅读1分钟
  1. Reaching Points Hard

290

61

Favorite

Share A move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y).

Given a starting point (sx, sy) and a target point (tx, ty), return True if and only if a sequence of moves exists to transform the point (sx, sy) to (tx, ty). Otherwise, return False.

Examples: Input: sx = 1, sy = 1, tx = 3, ty = 5 Output: True Explanation: One series of moves that transforms the starting point to the target is: (1, 1) -> (1, 2) (1, 2) -> (3, 2) (3, 2) -> (3, 5)

Input: sx = 1, sy = 1, tx = 2, ty = 2 Output: False

Input: sx = 1, sy = 1, tx = 1, ty = 1 Output: True

思路:如果tx>ty,说明最后一步是tx=tx+ty,那就tx对ty求余,排除ty,循环 如果tx==sx,说明tx目前的值即为最小值,(ty-tx)%sy == 0,说明可以,否则不可以

代码:python3

class Solution:
    def reachingPoints(self, sx, sy, tx, ty) :
        x=tx
        y=ty
        if sx==tx and sy==ty:
            return True
        while (y>=sy and x>=sx):
            if y>x:
                y=y%x
            else:
                x=x%y
        if x>y:
            return x==sx and y==sy%sx
        return y==sy and x==sx%sy
if __name__ == '__main__':
    print(Solution().reachingPoints(3,3,12,9))