递归详解
作者:互联网
递归详解
在计算机科学领域, 递归是用于处理一类具有相同子问题处理方式的问题;
是数学归纳法, 数学递推公式在计算机中的应用
The power of recursion evidently lies in the possibility of defining an infinite set of objects by a finite statement. In the same manner, an infinite number of computations can be described by a finite recursive program, even if this program contains no explicit repetitions.
--- by Niklaus Wirth, Algorithms + Data Structures = Programs, 1976
用递归的方法来解决问题的关键, 在于准确找到子问题
递归的简单应用
1. 阶乘
计算 \(n! = n *(n-1)* \dots *2* 1\)
即令 \(f(n) = n * f(n-1)\)
void Recursion_Factorial(int n)
{
if(n == 1) return n;
return n * Recursion_Factorial(n-1);
}
2. 寻找所有子集
template<class T>
void Recursion_Subset(vector<T> dataSet, vector<vector<T>>& result)
{
if (dataSet.empty()) { result.push_back({}); }
else
{
T data = dataSet.back();
dataSet.pop_back();
Recursion_Subset(dataSet, result);
int size = result.size();
for (int i = 0; i < size; i++)
{
result.push_back(result[i]);
result.back().push_back(data);
}
}
return;
}
标签:递归,Recursion,back,dataSet,详解,result,size 来源: https://www.cnblogs.com/InfField/p/16642715.html