Using Backward Reasoning to Solve the "Getting to the End" Problem

7. Reach the end point

7.1. Requirements for the title

​​ Given four integers sx , sy , tx and ty, return true if it is possible to get from the starting point (sx, sy) to the ending point (tx, ty) through a series of transitions, false otherwise. From point (x, y) can be converted to (x, x+y) or (x+y, y).

示例 1:
输入: sx = 1, sy = 1, tx = 3, ty = 5
输出: true

解释:
可以通过以下一系列转换从起点转换到终点:
(1, 1) -> (1, 2)
(1, 2) -> (3, 2)
(3, 2) -> (3, 5)

示例 2:
输入: sx = 1, sy = 1, tx = 2, ty = 2 
输出: false

示例 3:
输入: sx = 1, sy = 1, tx = 1, ty = 1 
输出: true

提示:
1 <= sx, sy, tx, ty <= 109

Source: LeetCode
Link: https://leetcode-cn.com/problems/reaching-points

7.2. Problem solving ideas

​​ This question uses the reverse reasoning operation, first perform the reverse operation on (tx, ty), until the reverse operation cannot be performed (it will eventually be pushed to the next state of (sx, sy)), then you can proceed to the next step Operation, calculate and judge the state derived from the above conclusion and (sx, sy), and obtain the boolean value.

Please add image description

7.3. Algorithms

class Solution {
    
    
    public boolean reachingPoints(int sx, int sy, int tx, int ty) {
    
    
        //将(tx,ty)进行反向操作,直到无法进行反向操作,就可以进行下一步
        //最终将会推至(sx,sy)的下一个状态
        while(tx > sx && ty > sy && tx != ty){
    
    
            if(tx > ty)
                //上一个状态为(tx - ty,ty)
                tx %= ty;
            else
                //上一个状态为(tx,ty - tx)
                ty %= tx;
        }
        //将上述结论推出的状态与(sx,sy)进行计算与判断,得出boolean值
        if(tx == sx && ty == sy){
    
    
            //两组数均相对应的相等,故两数组相等
            return true;
        }else if(tx == sx){
    
    
            return ty > sy && (ty - sy) % tx == 0;
        }else if(ty == sy){
    
    
            return tx > sx && (tx - sx) % ty == 0;
        }else{
    
    
            return false;
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_52916408/article/details/124108822