zoukankan      html  css  js  c++  java
  • 递归的应用实验一

    1.//1 1 2 3 5 8 13 21...
    #include <stdio.h>

    int fibonacci(int n)
    {
        if( n > 1 )
        {
            return fibonacci(n-1) + fibonacci(n-2);
        }
        else if( n == 1 )
        {
            return 1;
        }
        else if( n == 0 )
        {
            return 0;
        }
    }

    int main()
    {
        int i = 0;
        
        for(i=1; i<=10; i++)
        {
            printf("fibonacci(%d) = %d ", i, fibonacci(i));
        }
        
        return 0;
    }

    2.#include <stdio.h>

    void hanoi(int n, char a, char b, char c)
    {
        if( n > 0 )
        {
            if( n == 1 )
            {
                printf("%c -> %c ", a, c);
            }
            else
            {
                //a借助于c移动b
                hanoi(n-1, a, c, b);
                
                printf("%c -> %c ", a, c);
                
                hanoi(n-1, b, a, c);
            }
        }
    }

    int main()
    {
        hanoi(3, 'a', 'b', 'c');
        
        return 0;
    }

    3.#include <stdio.h>

    int strlen(const char* s)
    {
        if( s == NULL )
        {
            return -1;
        }
        else if( *s == '' )
        {
            return 0;
        }
        else
        {
            return strlen(s+1) + 1;
        }
    }

    int main()
    {
        printf("strlen("12345") = %d ", strlen("12345"));
        printf("strlen(NULL) = %d ", strlen(NULL));
        printf("strlen("") = %d ", strlen(""));
        
        return 0;
    }

    4.//全排列 abc--:有八种排列
    #include <stdio.h>

    void permutation(char s[], int b, int e)
    {
        if( (0 <= b) && (b <= e) )
        {
            if( b == e )
            {
                printf("%s ", s);
            }
            else
            {
                int i = 0;
                
                for(i=b; i<=e; i++)
                {
                    char c = s[b];
                    s[b] = s[i];
                    s[i] = c;
                    
                    permutation(s, b+1, e);
                    //交换回来
                    c = s[b];
                    s[b] = s[i];
                    s[i] = c;
                }
            }
        }
    }

    int main()
    {
        char s[] = "abcd";
        //3 表示字符的长度
        permutation(s, 0, 3);
        
        return 0;
    }

  • 相关阅读:
    python-- socket介绍
    Vue--element实现删除会员功能
    Vue--element实现编辑会员功能
    git clone速度过慢!
    Codeforces Round #730 (Div. 2) A/B/C/D1 解题思路
    KYOCERA Programming Contest 2021(AtCoder Beginner Contest 200) E
    Codeforces Round #719 (Div. 3) 解题报告
    ZJNU 1265
    PTA L3
    Codeforces 1503B/1504D
  • 原文地址:https://www.cnblogs.com/wxb20/p/6142495.html
Copyright © 2011-2022 走看看