1 递归
参考:https://mp.weixin.qq.com/s/mJ_jZZoak7uhItNgnfmZvQ
首先要读懂题->寻找到递归结束到条件->判断递归到规律。
1.1 斐波那契数列
#include <iostream>
using namespace std;
/*
斐波那契数列的是这样一个数列:1、1、2、3、5、8、13、21、34….,
即第一项 f(1) = 1,第二项 f(2) = 1…..,第 n 项目为 f(n) = f(n-1) + f(n-2)。求第 n 项的值是多少。
*/
int fib(int n){
if (n <= 2) return 1;
return fib(n-1) + fib(n-2);
}
int main(){
int n = 100;
int res = 0;
res = fib(n);
cout << "Result:" << res << endl;
return 0;
}
1.2 青蛙上台阶
#include <iostream>
using namespace std;
/*一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法
*/
int flog(int n){
// flog(0) == 0; flog(1) == 1; flog(2) == 2;
if (n <= 2) return n;
return flog(n-1) + flog(n-2);
}
int main(){
int n = 4;
int res = 0;
res = flog(n);
cout << res << endl;
return 0;
}
1.3 反转链表
#include <iostream>
using namespace std;
/*反转单链表。例如链表为:1->2->3->4。反转后为 4->3->2->1
*/
// class Node{
// public:
// int data;
// Node *next;
// };
struct Node{
int val;
struct Node *next;
Node(int x):
val(x), next(NULL){}
};
Node *Function(Node *head){
if (head == NULL || head->next == NULL) return head;
Node *temp = Function(head->next); // 此处为循环到链表到操作
head->next->next = head; // 修改当前节点的指向
head->next = NULL; // 断开原有节点
return temp;
}
int main(){
Node *node1 = new Node(1);
Node *node2 = new Node(3);
Node *node3 = new Node(5);
Node *node4 = new Node(7);
Node *node5 = new Node(9);
node1->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = node5;
Node *head = Function(node1);
while (head!=NULL && head->next!=NULL){
cout << head->val << "-";
head = head->next;
}
cout << head->val << endl;
return 0;
}