递归的应用实验一

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\n", 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\n", a, c);
        }
        else
        {
            //a借助于c移动b
            hanoi(n-1, a, c, b);
            
            printf("%c -> %c\n", 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 == '\0' )
    {
        return 0;
    }
    else
    {
        return strlen(s+1) + 1;
    }
}

int main()
{
    printf("strlen(\"12345\") = %d\n", strlen("12345"));
    printf("strlen(NULL) = %d\n", strlen(NULL));
    printf("strlen(\"\") = %d\n", 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\n", 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;
}

转载于:https://www.cnblogs.com/wxb20/p/6142495.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值