on
Lightoj problem 1189 sum of factorials
Read the problem several times to understand the input constraints present. By observing deeply we can know for sure that, given the input size if small (the largest factorial we will need is 20!) so here we can generate all the possible factorials and use bitmasking (or recursion) to pre-calculate all possible values and cache them … then for every case we just output the answer.
I’ve solved it with a greedy approach. Since, fact(n) > fact(0)+fact(1)+…+fact(n-1) (this is true for each n > 2) we can iterate from the greatest factorial(20!) to the smallest one, if fact[i] is less than or equal to N we must take it, decrease N by fact[i] and proceed with the next factorial. At the end, if N is 0 we found the solution, otherwise it is impossible to obtain N adding factorials.