1
+ // given a target an an array of non-negative integers, return a combination of values that sum up to the target value.
2
+ // the numbers can be used repeatedly. If no combination possible return NULL
3
+
4
+ // Time: O(m * n * m) (iterating through table * iterating through nums * copying array elements at a new location)
5
+
6
+
7
+ #include < iostream>
8
+ #include < vector>
9
+ using namespace std ;
10
+
11
+ // method overloading for createVector()
12
+
13
+ // simply creates a new vector without any entries
14
+ vector<int >* createVector (){
15
+ vector<int > *new_v = new vector<int >();
16
+ return new_v;
17
+ }
18
+
19
+ // create a new vector and copies the values from the vector passed as parameter
20
+ vector<int >* createVector (vector<int > prev){
21
+ vector<int > *new_v = new vector<int >();
22
+
23
+ for (int x: prev){
24
+ new_v->push_back (x);
25
+ }
26
+ return new_v;
27
+ }
28
+
29
+ vector<int >* howSum_tab (int target, vector<int > arr) {
30
+ // init a vector of vectors where each subvector has -1
31
+ vector<vector<int >*> table (target+1 , nullptr );
32
+
33
+ // set the first element of the table to an empty vector
34
+ table[0 ] = createVector ();
35
+
36
+ for (int i=0 ; i< table.size (); i++){
37
+ // for valid/true positions
38
+ if (table[i] != nullptr ){
39
+ // iterate over all possible shifts (i.e., arr values)
40
+ for (int j=0 ; j<arr.size (); j++){
41
+ // check for out of bounds
42
+ if (i + arr[j] < table.size ()){
43
+ // copy over the previous array at position i
44
+ table[i + arr[j]] = createVector (*table[i]); // this step accounts for the last 'm' factor in time complexity
45
+ // insert the new element arr[j]
46
+ table[i + arr[j]]->push_back (arr[j]);
47
+ }
48
+ }
49
+ }
50
+ }
51
+ return table[target];
52
+ }
53
+
54
+ int main () {
55
+
56
+ int n, iter = 1 , temp, target;
57
+ cout<<" Enter number of elements in array: " ;
58
+ cin>>n;
59
+
60
+ vector<int > arr;
61
+ while (iter <= n) {
62
+ cout<<" Enter element " <<iter<<" : " ;
63
+ cin>>temp;
64
+ arr.push_back (temp);
65
+ ++iter;
66
+ }
67
+
68
+ cout<<" Enter target: " ;
69
+ cin>>target;
70
+
71
+ vector<int > *res = howSum_tab (target, arr);
72
+
73
+ if (res == nullptr )
74
+ cout<<target<<" cannot be generated from array" <<endl;
75
+ else {
76
+ cout<<target<<" can be generated from array elements [ " ;
77
+ for (int num : *res){
78
+ cout<<num<<" " ;
79
+ }
80
+ cout<<" ]" <<endl;
81
+ }
82
+
83
+ return 0 ;
84
+ }
0 commit comments