geelaw
2017-06-02 10:04:49 +08:00
要把一个非递归函数写成递归,那是很容易的,举个例子:
```C++
template <typename TIt>
std::string const theAlgo(TIt &&begin, TIt &&end)
{
std::string result;
std::string helper1{"<"},helper2{">"},helper3{"</"};
for (; begin != end; ++begin) result = helper1 + *begin + helper2 + result + helper3 + *begin + helper2;
return std::move(result);
}
```
上面是非递归,下面是递归:
```C++
template <typename TIt>
std::string const theAlgo(TIt &&begin, TIt &&end, bool shouldWork = true)
{
if (!shouldWork) return "";
theAlgo(std::forward(begin), std::forward(end), false);
std::string result;
std::string helper1{"<"},helper2{">"},helper3{"</"};
for (; begin != end; ++begin) result = helper1 + *begin + helper2 + result + helper3 + *begin + helper2;
return std::move(result);
}
```
只要制造一个没用的调用即可。
当然,题目不是这个意思,实际上我可以写(伪代码):
```自然语言
TheAlgo(array, pos = 0)
____if (pos == array.length) return "";
____return "<" + array[pos] + ">" + TheAlgo(array, pos + 1) + "</" + array[pos] + ">";
```
就是把循环变成递归,很无聊。