开发者社区> 问答> 正文

怎么用递归函数实现这张图(用C语言编写)?顺便教一下运用递归算法的技巧。?

怎么用递归函数实现这张图(用C语言编写)?顺便教一下运用递归算法的技巧。?

展开
收起
知与谁同 2018-07-21 11:12:52 1437 0
1 条回答
写回答
取消 提交回答
  • #include <iostream>
    #include <algorithm>
    #include <string>
    #include <cstdlib>
    #include <set>
    #include <cmath>
    #include <cstdio>
    #include <cstring>
    #include <vector>
    #include <map>
    #include <stack>
    #include <queue>
    #include <cctype>
    #define LL long long
    using namespace std;
    const LL inf = 1e18;
    const LL mod = 1e9+7;
    int s[10] = {1, 3, 6, 10, 15, 21, 27};
    int m;
    void f(int n, int k, int cnt) {
    if(n == 1) {
    return;
    }
    else if(cnt == 0) {
    cnt = m - k - 1;
    k = m;
    f(cnt + 1, k, cnt);
    printf("%d\n", cnt + 1);
    }else {
    f(n + k, k - 1, cnt - 1);
    printf("%d ", n + k);
    }
    }
    int main() {
    //1 3 6 10 15 21 27
    //1 2 3 4  5  6  7
    //s = (1 + n) * n / 2
    int n;
    while(scanf("%d", &n) != EOF) {
    int k = lower_bound(s, s + 7, n) - s;
    m = k;
    f(k + 1, k, k);
    printf("%d\n", k + 1);
    }
        return 0;
    }

    效果

    仓促之间写出,也就这样了

    这问题实在是有意思啊,主要是比较忙,我其实还想好好想想,为了财富值直接回答了

    请用c++来编译,也就是g++编译器,头文件有的没用,懒得去掉了,你可以输入类似这种格式的数据来试验,不过最大也就是数组里面最大的,别超出。

    注:输入数据格式请看代码s数组

    写的不太好,不要介意

    求采纳,谢谢

    2019-07-17 22:55:03
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
数据+算法定义新世界 立即下载
袋鼠云基于实时计算的反黄牛算法 立即下载
Alink:基于Apache Flink的算法平台 立即下载