-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path19_CountSubsetWithSumk.cpp
78 lines (67 loc) · 1.8 KB
/
19_CountSubsetWithSumk.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/
// You are given an array of integers nums and an integer target.
// Return the number of non-empty subsequences of nums such that the
// sum of the minimum and maximum element on it is less or equal to target.
// Since the answer may be too large, return it modulo 109 + 7.
#include <bits/stdc++.h>
using namespace std;
class Solution1
{
// Recursion optimised
public:
int numSubseq(vector<int> &nums, int target)
{
int n = nums.size();
return solve(nums, target, n - 1);
}
int solve(vector<int> nums, int target, int i)
{
if (i == 0)
return nums[i] == target;
if (target == 0) return 1 ;
// Pick : Dont pick if nums[i] > target
int p = 0;
if (nums[i] <= target)
p = solve(nums, target - nums[i], i - 1);
// noPick
int np = solve(nums, target, i - 1);
return p + np;
}
};
class Solution
{
// BruteForce Solution : Recursion
public:
int numSubseq(vector<int> &nums, int target)
{
int n = nums.size(), count = 0;
solve(nums, count, target, n - 1);
return count;
}
void solve(vector<int> nums, int &count, int target, int i)
{
if (i < 0)
{
if (target == 0)
{
++count;
}
return;
}
// pick
solve(nums, count, target - nums[i], i - 1);
// not pick
solve(nums, count, target, i - 1);
}
};
int main()
{
// 1,2,3 | 1,5 | 2,4 | 6 ---> 4 ;
vector<int> nums = {1, 4, 3, 2, 5, 6};
int target = 6;
Solution1 Obj1;
cout << Obj1.numSubseq(nums, target);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}