递归在这段代码中是如何工作的?

时间:2016-05-27 04:40:45

标签: c++ recursion

// interleaving of two string

#include<bits/stdc++.h>

using namespace std;

bool isinterleav(string & a, string & b, string & c, int i, int j, int k) {

    if(i == -1 && k == -1 && j == -1) return true;

    bool x = false, y = false ;
    if(a[i] == c[k]) x = isinterleav(a,b,c,i-1,j,k-1);
     //cout <<  x <<" " <<  y << " " << i << " " << j << " " << k <<   endl;
    if(b[j] == c[k]) y = isinterleav(a,b,c,i,j-1,k-1);
    return x || y;
}

int main() {

    string a = "AFGHA", b = "ABCDA", c = "AFGHAABCDA";
    int i, j, k;
    //cin >> a >> b >> c;

    i = a.length()-1;
    j = b.length()-1;
    k = c.length()-1;

    if(isinterleav(a,b,c,i,j,k))
        cout << "Yes" << endl;
    else cout << "No" << endl;

    return 0;
}

2 个答案:

答案 0 :(得分:1)

我花了一些时间才明白代码在做什么。程序正在检查字符串C是字符串A和字符串B的组合,是否交错在一起。

递归方法是比较结尾的字符串,并检查当前结束字符是否与b中的当前结束字符中的当前结束字符相同。如果两个组合中的字符相同,它会使索引前进以检查结尾的下一个字符。

如果C是A和B的完美交错,则递归以true结束。否则以false结束。

希望这有帮助。

答案 1 :(得分:0)

这是我的想法,希望它会有所帮助:

#include <iostream>
using namespace std;

bool isinterleav(string & a, string & b, string & c, int i, int j, int k) {
if(i == -1 && k == -1 && j == -1) return true;

bool x = false, y = false ;
if(a[i] == c[k]) x = isinterleav(a,b,c,i-1,j,k-1);
//cout <<  x <<" " <<  y << " " << i << " " << j << " " << k <<   endl;
/*it will inspect the next i and k till can't inspect anymore
In your case: i=-1,k=5,x=false that you set before ;*/
if(b[j] == c[k]) y = isinterleav(a,b,c,i,j-1,k-1);
 /* and it will continue doing this with j and k with k=5 till can't inspect anymore 
 In your case j=-1,k=-1,i=-1 =>y=true  */
 return x || y; //and your case is True||false => True

 }
 int main() {

 string a = "AFGHA", b = "ABCDA", c = "AFGHAABCDA";
 int i, j, k;
 //cin >> a >> b >> c;

 i = a.length()-1;
 j = b.length()-1;
 k = c.length()-1;

 if(isinterleav(a,b,c,i,j,k))
   cout << "Yes" << endl;
  else cout << "No" << endl;

 return 0;
}

抱歉我的英语不好!