LeetCode刷题--Reaching Points

2018-02-17  本文已影响29人  faris_shi

1. 题目

原题地址

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

Note:

2。 方案

2.1 思路一 正向思维

采用递归的方式,通过不断的试探穷举遍历。

class Solution {
    public boolean reachingPoints(int sx, int sy, int tx, int ty) {

        if (tx == sx && ty == sy) {
            return true;
        }
        
        if(tx > sx || ty > sy){
            return false;
        }
        return reachingPoints(sx + sy, sy, tx,ty) || reachingPoints(sx , sx + sy, tx,ty);
    }
}

2.2 思路二 逆向思维

二叉树 的思路考虑问题,每一个节点 (x, y) 都有两个子节点 (x+y, y)(x, x + y)。而每一个节点(x, y)只有一个父节点, 如果x > y 父节点为 (x - y, y), 否则为 (x, y - x)

class Solution {
    public boolean reachingPoints(int sx, int sy, int tx, int ty) {

        while (tx >= sx && ty >= sy) {
            if (tx == sx && ty == sy) {
                return true;
            }
            if (tx > ty) {
                tx = tx - ty;
            } else {
                ty = ty - tx;
            }
        }
        return false;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读