递归置换,Ellis Horowitz算法和数据结构混乱。

时间:2013-04-02 19:47:18

标签: c++ algorithm data-structures recursion non-recursive

我是大学一年级的初级程序员。我的导师要求我们对递归算法进行一些研究,并使其无法递归。不管我多少尝试它似乎是不可能的。 问题是

  

A是字符串(例如A =“hello”)和交换,即   抽象,用第i个字符交换第k个,   例如CALL交换(“你好”,2,3)会改变“你好”   “hlelo”)。

这个想法是打印出所有可能的排列 c ++中的版本读取

void perm(char*a, const int k, const int n)
{
  if(k==n)
  {
    cout << a;
  }
  else
  {
    for (i=k;i<=n;i++)
    {
      interchange(a, k, i);
      perm(a, k+1, n)
    }
  }
 }

我的导师更喜欢使用一种名为ADL的语言,这种语言似乎只出现在Horowitz的“算法和数据结构”一书中。他在ADL中提出了这个问题,所以我也会添加这些代码,这很容易理解。

proc perm(IN a, IN k, IN n)
  if k=n then
    print(a)
  else
    {
     for i <- k to n do
       call interchange(a,k,i)
       call perm( a, k+1, n)
     end
    }
end

感谢任何可以提供帮助的人。 马丁

2 个答案:

答案 0 :(得分:2)

这是一个暗示,没有为你做功课。当你沿着弦走,看着第i个角色时,你处于以下三种状态之一:

  • i == k
  • i == n
  • 否则

在这三种情况下,你打印什么?

答案 1 :(得分:2)

递归算法只是使用堆栈的算法。

递归允许您使用call stack作为数据堆栈。

采用这种形式的任何递归函数:

void perm(char*a, const int k, const int n)
{
   // check if your code should return

   // make a recursive call with new data
}

可以改为:

void perm(char*a, const int k, const int n)
{
   // Create a stack, push (a,k,n)

   while ( /* stack isn't empty */ )
   {
       // check if stack should be *popped* (instead of returning)

       // Put new data on the stack (instead of recursing)
   }
}
相关问题