c++ - Recursive sum of subsets -
i have read through other discussions, cannot figure how fix program. recurses, index counter gets large , promising not work since out of bounds (or @ least believe correct). how can fix such index never gets large?
vector<uint> w; // vector of weights vector<bool> include; uint w; // desired weight uint index = 0; uint weight = 0; // current weight of subsets uint total = 0; // superset total void sum_of_subsets( uint index, uint weight, uint total, vector<bool> &include, vector<uint> &w, uint w ) { if( promising(index, weight, w, w, total) ) { if( weight == w ) { for( uint k = 0; k <= include.size(); k++ ) { if(include.at(k)) cout << w.at(k) << " "; } } else { include.at(index + 1) = 1; sum_of_subsets( index + 1, weight + w.at(index + 1 ), total - w.at(index + 1), include, w, w ) ; include.at(index + 1) = 0; sum_of_subsets( index + 1, weight, total - w.at(index + 1), include, w, w ); } } } bool promising ( uint index, uint weight, uint w, vector<uint> w, uint total ) { return ( weight + total >= w ) && ((weight == w) || (weight + w.at(index+1) <= w)); }
Comments
Post a Comment