LWC 71: 780. Reaching Points

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014688145/article/details/79312470

LWC 71: 780. Reaching Points

传送门:780. Reaching Points

Problem:

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.

Example:

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

Note:

sx, sy, tx, ty will all be integers in the range [1, 10^9].

思路:
先说说简单的,直接根据题目的意思来,递归求解,如下:

    public boolean reachingPoints(int sx, int sy, int tx, int ty) {
        return f(sx, sy, tx, ty);
    }

    boolean f(int sx, int sy, int tx, int ty) {
        if (tx < sx || ty < sy) return false;
        if (tx == sx && ty == sy) return true;
        if (f(sx, sx + sy, tx, ty) || f(sx + sy, sy, tx, ty)) return true;
        return false;
    }

stack over flow,原因很简单,如例子[5, 7, 455955547, 420098884],想想它的递归深度。

我们观察式子(x, y) -> (x + y, y) or (x, x + y),如果两者交替相加,那递归深度大是必然的,但很多情况下可以这么transform:

(x, y) -> (x + y, y) -> (x + 2y, y) -> (x + 3y, y)

那么当存在tx很大的情况时,我们可以发现tx直接余上ty就能直接省去若干的叠加。那么递归深度也以指数级减少。

比如 (x + 3y) % y = x, 所以只需要一步从(x + 3y, y) -> (x, y)

代码如下:

    public boolean reachingPoints(int sx, int sy, int tx, int ty) {
        return f(sx, sy, tx, ty);
    }

    boolean f(int sx, int sy, int tx, int ty) {
        if (tx < sx || ty < sy) return false;
        if(sy == ty && (tx-sx) % sy == 0) return true;
        if(sx == tx && (ty-sy) % sx == 0) return true;
        if (ty > tx) {
            if (f(sx, sy, tx, ty % tx)) return true;
        }
        else {
            if (f(sx, sy, tx % ty, ty)) return true;
        }
        return false;
    }

考虑下终止条件,因为不管 ty % tx, 还是 tx % ty, 都会归简到最初的情况,(x + ky, y) or (x, kx + y),在这种情况下,加个判断即可。

Python版本:

class Solution(object):
    def reachingPoints(self, sx, sy, tx, ty):
        """
        :type sx: int
        :type sy: int
        :type tx: int
        :type ty: int
        :rtype: bool
        """
        if tx < sx or ty < sy: return False
        if sx == tx and (ty - sy) % sx == 0: return True
        if sy == ty and (tx - sx) % sy == 0: return True
        if tx < ty: return self.reachingPoints(sx, sy, tx, ty % tx)
        else: return self.reachingPoints(sx, sy, tx % ty, ty)

猜你喜欢

转载自blog.csdn.net/u014688145/article/details/79312470
71
71A