BFS for arithmetic operations

后端 未结 3 1900
余生分开走
余生分开走 2021-01-24 08:35

Convert a number m to n with minimum operations. The operations allowed were subtraction by 1 and multiplication by 2.

For Eg : 4 and 6. Answer is 2. 1st operation : -1

3条回答
  •  醉梦人生
    2021-01-24 08:56

    This code hopefully implements the above-mentioned very efficient algorithm.

    private static int solve(int n, int m) {
    
    int steps = 0;
    int cur = n;
    ArrayList arr = new ArrayList<>();
    
    arr.add(m);
    for (int i = 0; !arr.contains(1); ++i)
        arr.add((int) Math.round((double) arr.get(i) / 2));
    
    while (cur != m) {
        if (arr.contains(cur))
            cur *= 2;
        else
            cur--;
    
        steps++;
       }
    
    return steps;
    }
    

    Explanation::

    Imagine a stair and starting from (n) you've got to reach its top (i.e: the number m), so you decided to make list of all the best steps to take, then you refer to the number you have and see if it exists in that list you made for an optimal solution, if it's there then you just follow the steps and you'll get the best solution, if not you'll have to align yourself to the optimal steps (say by subtracting 1) and then you're on the optimal track and vooooom to your destination. For more: please, refer to the explanation in mr.paul solution up there explains this better.

提交回复
热议问题