1 递归

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值