使用数组的元素查找总和'k'

find a sum 'k' using the elements of an array

本文关键字:查找 数组 元素      更新时间:2023-10-16

我是 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;
    }

但是上面的代码给了我真而不是假.有什么问题。 提前谢谢。

isSumreturn中,您希望使用逻辑和运算符&&而不是逻辑或运算符||。 您还需要单个元素的return