快速幂计算 Power Calculus

该篇文章介绍了如何使用递归函数`findPath`在给定整数序列中找到从1到达目标值n所需的最小步数,通过遍历并尝试加减序列中的元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目
照搬的题解,重命名了变量 ; -)

now >>(maxStep-step)的目的是让剩余步数都用来自*2,看看能不能够到n

#include <iostream>
using namespace std;
int maxStep,n;
int nums[50];

/// @brief 深度遍历查找可行路径,用的递归,要确认好基本情况和单位情况,应该每一个函数调用就是一次乘法或除法,包括第0步
/// @param step 当前已走步数
/// @param now 当前得到数值
/// @return 
bool findPath(int step,int now)
{
    if(now < 0 || step > maxStep || now <<(maxStep-step) < n)   return false;
    if(now==n || now >>(maxStep-step)==n)  return true;
    nums[step] = now;
    step++;
    for (int i = 0; i < step; i++)
    {
        if(findPath(step,now+nums[i]))    return true;
        if(findPath(step,now-nums[i]))    return true;
    }
    return false;
}

int main()
{
    while(1)
    {
        cin >> n;
        if(n==0)    break;
        for (maxStep = 0;!findPath(0,1) ; maxStep++);
        cout << maxStep << endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值