gpt4 book ai didi

c - 返回整数数组中可能性数量的函数

转载 作者:行者123 更新时间:2023-11-30 16:13:13 25 4
gpt4 key购买 nike

该函数接受一个整数数组、它的长度以及两个整数 N1 和 N2它应该返回一个整数,描述了可以通过多少种方式对数组的 N1 个元素求和以获得等于 N2 的总和。如何实现这个功能?

最佳答案

使用递归。例如。隐约类似于:

int findCount(int *array, int length, int N1, int N2) {
int count = 0;

if(N1 == 1) {
for(int i = 0; i < length; i++) {
if(array[i] == N2) {
count++;
}
}
} else {
for(int i = 0; i < length; i++) {
count += findCount(&array[i+1], length-i-1, N1 - 1, N2 - array[i]);
}
}
return count;
}

注意:如果数组不能包含零或负数,您可以使用 if(array[i] < N2) count += findCount(&array[i+1], length-i-1, N1 - 1, N2 - array[i]); 来改进它.

关于c - 返回整数数组中可能性数量的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58107647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com