利用递归和迭代求二项系数

1 使用递归方法

1.1递归方程和基础情况

基础情况:

if (n == m || m == 0) {
        return 1;
    }

递归方程:Recursion(m, n - 1) + Recursion(m - 1, n - 1)

1.2 代码

#include<stdio.h>
#include<stdlib.h>
int Recursion(int m,int n) {
    if (n == m || m == 0) {
        return 1;
    }
    else
        return Recursion(m, n - 1) + Recursion(m - 1, n - 1);
}
int main() {
    int m, n,ans;
    scanf("%d %d",&m,&n);
    ans = Recursion(m, n);
    printf("%d", ans);
    return 0;
}

2 使用迭代方法

2.1 原理

迭代核心过程,利用杨辉三角,进行动态规划转移,

2.2 代码

#include<stdio.h>
#include<stdlib.h>
int Iteration(int m,int n) {
    int ans = 0;
    int** iteration = (int**)malloc(n * sizeof(int*));

    for (int i = 0; i < n; i++) 
    {
        iteration[i] = (int*)malloc(n* sizeof(int));
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i == 0||i==j) {
                iteration[i][j] = 1;
            }
            else
                iteration[i][j] = 0;
        }
    }
    for (int i = 1; i<=m; i++) {
        for (int j = 1; j<=n; j++) {
            iteration[i][j]= iteration[i][j-1] + iteration[i - 1][j - 1];
        }
    }
    return iteration[m][n];
}
int main() {
    int m, n, ans;
    scanf("%d %d", &m, &n);
    ans = Iteration(m, n);
    printf("%d", ans);
    return 0;
}

3 总结

再利用递归和迭代求解问题是要弄清楚他们的递推公式和结束条件,递归的代码简短但是不易于理解。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
三元不定方程组可用递归的方法解,具体步骤如下: 1. 将三元不定方程组化为两个二元不定方程组。 2. 解出其中一个二元不定方程组。 3. 将第一步中解出的结果代入另一个二元不定方程组中,得到一个一元不定方程。 4. 解出第三步中的一元不定方程,得到一个变量的值。 5. 将第四步中得到的变量值代入第二步中解出的二元不定方程组中,得到另一个变量的值。 6. 将第五步中得到的变量值代入第一步中未解出的二元不定方程组中,得到第三个变量的值。 7. 得到三个变量的值,即为方程组的解。 以下是递归解三元不定方程组的示代码: ```python def solve_3_equations(a, b, c, d, e, f): if a == 0 and b == 0 and c == 0: # 当 a,b,c 都为 0 时,方程无解 return None if a == 0 and b == 0: # 当 a,b 都为 0 时,方程组化为一个一元不定方程 if f % c == 0: return [0, 0, f//c] else: return None if a == 0 and c == 0: # 当 a,c 都为 0 时,方程组化为一个一元不定方程 if e % b == 0: return [0, e//b, 0] else: return None if b == 0 and c == 0: # 当 b,c 都为 0 时,方程组化为一个一元不定方程 if d % a == 0: return [d//a, 0, 0] else: return None if a == 0: # 当 a 为 0 时,方程组化为一个二元不定方程 y, z = solve_2_equations(b, c, e, f) if y is None: return None else: return [0, y, z] if b == 0: # 当 b 为 0 时,方程组化为一个二元不定方程 x, z = solve_2_equations(a, c, d, f) if x is None: return None else: return [x, 0, z] if c == 0: # 当 c 为 0 时,方程组化为一个二元不定方程 x, y = solve_2_equations(a, b, d, e) if x is None: return None else: return [x, y, 0] # 当 a,b,c 都不为 0 时,先解出其中一个二元不定方程 x, y = solve_2_equations(a, b, d, e) if x is None: return None else: # 将 x 代入另一个二元不定方程中,得到一个一元不定方程 z = (f - c*y - b*x) // a return [x, y, z] ``` 其中 `solve_2_equations` 是解二元不定方程组的函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值