Given an array of N elements, check if it is possible to obtain a sum of S, by choosing some (or none) elements of the array and adding them.
Example:
Input: n = 5, arr[n] = {3, 2, 0, 7, -1}, sum = 8
Output: YES
Approach
C++
#include <bits/stdc++.h>using namespace std;void sumOfNumbers(long long n,long long arr[], long long sum){if (sum == 0)cout << "YES\n";else{int flag = 0;for (long long i = 0; i <= 1 << n; i++){long long ans = 0;for (long long j = 0; j < n; j++){if (i & 1 << j)ans += arr[j];}if (ans == sum){flag = 1;break;}}if (flag == 1)cout << "YES\n";elsecout << "NO\n";}}int main(){long long n = 5;long long arr[n] = {3, 2, 0, 7, -1};long long sum = 8;sumOfNumbers(n, arr, sum);return 0;}
No comments:
Post a Comment