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;
    }

  • 相关阅读:
    BZOJ2337 [HNOI2011]XOR和路径
    「学习笔记」3.31代码学习
    uva live 12846 A Daisy Puzzle Game
    Cannot use ImageField because Pillow is not installed
    Android点击Button水波纹效果
    hdu 1241 Oil Deposits
    c++ 字符输入读取
    clutter recoder
    C/C++获取数组长度
    vector array and normal stanard array
  • 原文地址:https://www.cnblogs.com/wxb20/p/6142495.html
Copyright © 2011-2022 走看看