How do I thoroughly understand Recursive Algorithm and not feel like recursion is magic?
Recursion is magic! But any sufficiently advanced technology is indistinguishable from magic!
what is tail-recursion?
This results in the last statement being in the form of (return (recursive-function params))
.
关于时间复杂度:
Are 2^n and n*2^n in the same time complexity?
The Three Laws of Recursion
Like the robots of Asimov, all recursive algorithms must obey three important laws:
- A recursive algorithm must call itself, recursively.
- A recursive algorithm must have a base case.
- A recursive algorithm must change its state and move toward the base case.
A base case is the condition that allows the algorithm to stop recursing.
- A base case is typically a problem that is small enough to solve directly.
- In the
factorial
algorithm the base case is n=1.
We must arrange for a change of state that moves the algorithm toward the base case.
- A change of state means that some data that the algorithm is using is modified.
- Usually the data that represents our problem gets smaller in some way.
- In the
factorial
n decreases.
编写代码前的思考:
- Break the problem I am trying to solve down into a problem that is one step simpler
- Assume that my function will work to solve the simpler problem — really believe it beyond any doubt
- Ask myself: Since I know I can solve the simpler problem, how would I solve the more complex problem?
One common mistake that I see people make when trying to develop a recursive algorithm to solve a problem is that they try to think about how to break the problem down all the way to the base case(递归条件).
I would like to emphasize that in order to develop the function above, I did not think about how I could break the problem down all the way to the base case. That is the function’s job, not yours. Instead, I only thought about the problem that is one step simpler than the problem I am really trying to solve, and then I wrote my recursive algorithm to build up from there to solve the real problem.
反转字符串 c++:
#include <iostream> #include <string> #include <vector> using namespace std; // 递归函数
string reverseString(vector<char>& vec){ // 递归条件 if(vec.size()< 2) return string(1,vec[0]); // 递归链条 vector<char> vec0; vec0.push_back(vec[0]); vec.erase(vec.begin()); return reverseString(vec) + reverseString(vec0); } int main(){ vector<char> vec; string s = "helloworld"; for(int i=0;i<(int)s.size();i++){ vec.push_back(s[i]); } string ret = reverseString(vec); cout << ret << endl; return 0; }