Algorithm to calculate the number of combinations to form 100

前端 未结 5 451
说谎
说谎 2020-12-08 23:13

I am struck in a tricky situation where I need to calculate the number of combinations to form 100 based on different factors.

Those are

  • Number of combin
5条回答
  •  甜味超标
    2020-12-09 00:00

    Why can't you use a brute force approach with few optimization? For example, say N - Number of combinations M - Multiples D - Max possible Distance

    So possible values in combinations can be M, 2M, 3M and so on. You need to generate this set and then start with first element from set and try to find out next two from choosing values from same set (provided that they should be less than D from first/second value). So with i/p of 3-10-30 would

    1. Create a set of 10, 20, 30, 40, 50, 60, 70, 80, 90 as a possible values
    2. Start with 10, choice for second value has to be 20, 30, 40, 50 (D < 30)
    3. Now choose second value from set of 20, 30, 40, 50 and try to get next value and so on

    If you use a recursion then solution would become even simpler.

    1. You have to find N values from a list of possible values within MIN & MAX index.
    2. So try first value at MIN index (to MAX index). Say we have chosen value at X index.
    3. For every first value, try to find out N-1 values from the list where MIN = X + 1 and MAX.

    Worst performance will happen when M = 1 and N is sufficiently large.

提交回复
热议问题