【问题标题】:using backtracking recursion c++使用回溯递归 C++
【发布时间】:2015-01-23 16:32:32
【问题描述】:

我需要帮助来编写 C++ 中的回溯递归代码,以达到从 1 个数字到其他数字的最小步骤。您只能使用 +1 或 *2 例如,最短从 10 得到 23 是:((10+1)*2)+1 有 3 个步骤, 或从 12 得到 65: (((12+1+1+1+1)*2)*2)+1 有 7 个步骤

TNX。

【问题讨论】:

  • 如果你看这两天的帖子,还有一个类似的帖子,关于最短步数,使用迭代。重要的部分是它使用数学函数进行了简化。在 StackOverflow 中搜索“c++ 最短步骤”

标签: c++ algorithm recursion backtracking


【解决方案1】:

这里有一些帮助,基本的递归函数:

void recursive(unsigned int count)
{
  // Need to determine the end of recursion.
  if (count == 0)
  {
     return;
  }

  // Call the function again, which is recursion.
  recursive(count - 1);
}

在此模型的基础上确定如何实现您的要求。

提示:使用递归,一次一步。在一张纸上,写下执行的每个步骤以及所有值,直到操作完成。查看最后一步以确定如何停止递归。

【讨论】:

    【解决方案2】:
    int goal=23;
    int result=1e9; ## set the count to infinity to optimize it
    void solve(int curNumber,int step){
     if(goal == curNumber)  // Check if we reached the goal number
       result=min(result,step); // take the min of the solution, and number of   steps we took to reach the goal
     curNumber+=1  // add 1 to current Number
     solve(curNumber,step+1);
     curNumber-=1;   // backtrack on the add 1 solution
     curNumber*=2;  // choose the other path *2
     solve(curNumber, step+1);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      相关资源
      最近更新 更多