数据结构研究之四 递归

1.递归:
递归就是把一个问题拆分成两个或多个更小的问题,先求出每个局部问题的解然后再将结果整合。

例题:计算长度为n的数列中是否能加起来到得到某个指定值。

//
// Created by 叶子 on 2018/1/27.
//

#include "stdio.h"

int N,a[50];

int solve(int i,int m){
    if ( m == 0 ) return 1;
    if ( i>= N )  return 0;
    int res = solve(i+1,m) || solve(i+1,m-a[i]);
    return res;
}

int main(){
    int q,m,i;

    scanf("%d",&N);
    for ( i = 0 ; i < N ; i ++) scanf("%d",&a[i]);
    scanf("%d",&q);
    for ( i = 0 ; i < q ; i ++){
        scanf("%d",&m);
        if ( solve(0,m)) printf("yes\n");
        else printf("No\n");
    }
}


2.递归的深入:科赫曲线

//
// Created by 叶子 on 2018/1/27.
// 科赫曲线
//

#include "stdio.h"
#include "math.h"

struct Point{ double x,y;};

void koch(int n ,Point a,Point b){
    if ( n == 0 ) return ;

    Point s,t,u;
    double th = M_PI * 60.0 / 180.0; 

    s.x = ( 2.0*a.x + 1.0*b.x)/3.0;
    s.y = ( 2.0*a.y + 1.0*b.y) /3.0;
    t.x = ( 1.0 * a.x + 2.0*b.x) / 3.0;
    t.y = ( 1.0 * a.y + 2.0 * b.y ) / 3.0;
    u.x = (t.x - s.x) * cos(th) - (t.y - s.y)*sin(th)+ s.x;
    u.y = (t.x - s.x) * sin(th) - (t.y - s.y)*cos(th) + s.y;

    koch(n-1,a,s);
    printf("%.8f %.8f\n",s.x,s.y);
    koch(n-1,s,u);
    printf("%.8f %.8f\n",u.x,u.y);
    koch(n-1,u,t);
    printf("%.8f %.8f\n",t.x,t.y);
    koch(n-1,t,b);
}

int main(){
    Point a,b;
    int n;

    scanf("%d",&n);

    a.x = 0 ;
    a.y = 0;
    b.x = 100;
    b.y = 0 ;

    printf("%.8f %.8f\n",a.x,a.y);
    koch(n,a,b);
    printf("%.8f %.8f\n",b.x,b.y);

    return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值