1
+ // given a target an an array of non-negative integers, return the smallest 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
+ #include < iostream>
5
+ #include < vector>
6
+ using namespace std ;
7
+
8
+ vector<int >* createVector () {
9
+ vector<int > *new_v = new vector<int >();
10
+ return new_v;
11
+ }
12
+
13
+ // create a new vector and copies the values from the vector passed as parameter
14
+ vector<int >* createVector (vector<int > prev){
15
+ vector<int > *new_v = new vector<int >();
16
+
17
+ for (int x: prev){
18
+ new_v->push_back (x);
19
+ }
20
+ return new_v;
21
+ }
22
+
23
+ // compare two vectors to see which is the shorter one
24
+ void compareAndProceed (vector<int > *potentialRes, vector<int > *originalRes, int ele){
25
+ return ;
26
+ }
27
+
28
+ vector<int >* bestSum_tab (int target, vector<int > arr) {
29
+ // init a vector of vectors where each subvector is initially nullptr
30
+ vector<vector<int >*> table (target+1 , nullptr );
31
+
32
+ table[0 ] = createVector ();
33
+
34
+ for (int i=0 ; i<table.size (); i++){
35
+ // continue only for valid/true positions
36
+ if (table[i] != nullptr ){
37
+ // iterate over all possible shifts (i.e., arr values)
38
+ for (int j=0 ; j<arr.size (); j++) {
39
+
40
+ // check for out of bounds
41
+ if (i + arr[j] < table.size ()){
42
+ // compare the length between the result at new position (if any) and the potential result in this iteration
43
+ // null -> no comparison simply copy, else compare size and copy if potential result is shorter
44
+ if (table[i + arr[j]] == nullptr
45
+ || table[i + arr[j]]->size () > table[i]->size ())
46
+ {
47
+ table[i + arr[j]] = createVector (*table[i]);
48
+ table[i + arr[j]]->push_back (arr[j]);
49
+ }
50
+ }
51
+ }
52
+ }
53
+ }
54
+ return table[target];
55
+ }
56
+
57
+
58
+ int main () {
59
+
60
+ int n, iter = 1 , temp, target;
61
+ cout<<" Enter number of elements in array: " ;
62
+ cin>>n;
63
+
64
+ vector<int > arr;
65
+ while (iter <= n) {
66
+ cout<<" Enter element " <<iter<<" : " ;
67
+ cin>>temp;
68
+ arr.push_back (temp);
69
+ ++iter;
70
+ }
71
+
72
+ cout<<" Enter target: " ;
73
+ cin>>target;
74
+
75
+ vector<int > *bestRes = bestSum_tab (target, arr);
76
+
77
+ if (bestRes == nullptr )
78
+ cout<<target<<" cannot be generated from array" <<endl;
79
+ else {
80
+ cout<<target<<" can be generated from array elements: " ;
81
+ for (int num : *bestRes){
82
+ cout<<num<<" " ;
83
+ }
84
+ cout<<endl;
85
+ }
86
+
87
+ return 0 ;
88
+ }
0 commit comments