使用数组的元素查找总和'k'
find a sum 'k' using the elements of an array
我是 C++ 的新手。 我试图在数字数组中找到一个总和"k"。 我正在使用递归来查找"k"是否可以使用任何 no。 在数组中。我编写了以下代码。
#include<iostream>
using namespace std;
bool isSum(int arr[],int low,int size, int k)
{
if(k == 0)
return true;
if(size == 0)
return false;
#using recursion , one recursion including the present no. in the array, another excluding the present no.
return (isSum(arr,low +1, size-1,k-arr[low]) || isSum(arr, low + 1, size -1 ,k));
}
int main()
{
int arr[] = {261, 823, 126, 57, 826, 57, 47, 716, 146, 439, 15, 34, 238, 10, 690, 213, 292, 10, 16, 711};;
bool a = isSum(arr,0,20, 512);
if(a)
cout<<"true"<<endl;
else
cout<<"false"<<endl;
}
但是上面的代码给了我真而不是假.有什么问题。 提前谢谢。
在isSum
的return
中,您希望使用逻辑和运算符&&
而不是逻辑或运算符||
。 您还需要单个元素的return
。
相关文章:
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 需要使用模板查找数组的第二个最小和最小值
- 用于查找数组中最大元素的出现次数的代码,给出分段错误
- 查找数组中指示性较大但数组中值较小的元素
- C++ 函数,用于查找数组中四个最小最大元素的总和不起作用
- 查找数组中的最小数字
- 查找数组中重复(重复)数字的索引
- 使用一个内存集数组和单个堆栈在 O(n) 中查找数组的下一个更大元素
- 查找数组中给定数字的出现次数
- 使用 std::累加来查找数组的总和
- 代码以查找数组中的最大数字,但它仅将第一个数字显示为最大数字. 有人请告诉我为什么
- 在不进行排序的情况下查找数组中n个最小值的索引
- 当数组在C++中用作参数时,查找数组的元素数
- 查找数组中数组元素的重复出现?
- 查找数组最后 3 个数字的平均值
- 查找数组中是否存在C++元素
- 查找数组中的最小更改数以进行 k 算术级数
- 查找数组的第一个和最后一个索引,其中 from 和 to 元素的顺序总和最大
- 有没有办法在递归中使用指针来查找数组的最小值?
- 在编写代码以查找数组中的对数时获取分段错误