-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4-Sum Problem
37 lines (29 loc) · 984 Bytes
/
4-Sum Problem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;
// Naive recursive function to check if quadruplet exists in an array
// with the given sum
bool hasQuadruplet(int nums[], int n, int target, int count)
{
// if the desired sum is reached with 4 elements, return true
if (target == 0 && count == 4) {
return true;
}
// return false if the sum is not possible with the current configuration
if (count > 4 || n == 0) {
return false;
}
// Recur with
// 1. Including the current element
// 2. Excluding the current element
return hasQuadruplet(nums, n - 1, target - nums[n - 1], count + 1) ||
hasQuadruplet(nums, n - 1, target, count);
}
int main()
{
int nums[] = { 2, 7, 4, 0, 9, 5, 1, 3 };
int target = 20;
int n = sizeof(nums) / sizeof(nums[0]);
hasQuadruplet(nums, n, target, 0) ? cout << "Quadruplet exists":
cout << "Quadruplet Doesn't Exist";
return 0;
}