D
D
dmitriyivvvv2019-01-21 17:54:20
Mathematics
dmitriyivvvv, 2019-01-21 17:54:20

How to find all combinations that can form n?

Good evening! In general, there is some set [100, 50, 25, 10, 5, 1] ​​and n. I need to find all combinations that can form n. For example, for n = 100 and the set above, the answer is 194 combinations. Since I have trouble with algorithms, I don’t even know how to formulate it correctly in order to google it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Alekseev, 2019-01-21
@dmitriyivvvv

#include <iostream>
#include <vector>

std::vector<int> arr = { 100, 50, 25, 10, 5, 1 };
int n = 100;
int matches = 0;

void calc( int val, unsigned int offs ) {
  if( val == n ) {
    matches++;
    return;
  } else if( val > n ) {
    return;
  }
  for( unsigned int i = offs; i < arr.size(); ++i ) {
    calc( val + arr[i], i );
  }
}

int main( int argc, char** argv ) {
  calc( 0, 0 );
  std::cout << matches << std::endl;
  return( EXIT_SUCCESS );
}

V
Vladimir, 2019-01-21
@sovlarus

Maybe something like this: https://prog-cpp.ru/combinations/?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question