fewest number of operations needed to get to 1

复制代码
package _interview_question

import java.util.*

/**
 * The question is to find the fewest number of operations needed to get to 1.
available operations:
- add 1
- subtract 1
- divide by 2

Example 1:
input: 15, output: 5,
because: 15->16->8->4->2->1

Example 2:
input: 10, output: 4,
because: 10->5->4->3->2->1

Have any constraints?
 * */
class HelpNode(var value: Double) {
    var step: Int = 0
}

class Solution10 {
    /*
      solution:bfs, Time complexity:O(3^n), Space complexity:O(n)
    * */
    fun getToOne(num: Int): Int {
        val queue = LinkedList<HelpNode>()
        val node = HelpNode(num.toDouble())
        queue.offer(node)
        while (queue.isNotEmpty()) {
            val cur = queue.poll()
            if (cur.value == 1.0) {
                return cur.step
            }
            val add = cur.value + 1
            val subtract = cur.value - 1
            val divide = cur.value / 2//because divide, so we need double to keep correct
            //println("divide:${divide}")

            val addNode = HelpNode(add)
            addNode.step = cur.step + 1
            queue.offer(addNode)

            val subtractNode = HelpNode(subtract)
            subtractNode.step = cur.step + 1
            queue.offer(subtractNode)

            val divideNode = HelpNode(divide)
            divideNode.step = cur.step + 1
            queue.offer(divideNode)
        }
        return -1
    }
}
复制代码

 

posted @   johnny_zhao  阅读(114)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示