题目
照搬的题解,重命名了变量 ; -)
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;}
}