Algorithm question
The following array exists list = [1, 3, 6, 8, 12, 18, 25, 28, 30, 40, 45, 50, 60, 68, 78, 88, 98, 128, 158, 198, 248, 298 , 348, 418, 488, 548, 588, 618, 648, 698, 798, 818, 848, 898, 998, 1048, 1098, 1148, 1198, 1248, 1298, 1398, 1448, 149, 8, 1998 , 2298, 2598, 2998, 3298, 3998, 4498, 4998, 5898, 6498]
, the target
value is a number, you need to select the sum of n
numbers from list
as target
, n
The range is [1,10]
, where items in the list allow repeated selection, for example:
Example1: Assuming target = 10,
✅ Possible outcomes are as follows:
- Result 1:
10*1 = 10
, =>[1,1,1,1,1,1,1,1,1,1]
- Result 2:
1*8 + 2*1 = 10
, =>[8,1,1]
- Result 3:
1*6 + 3*1 + 1*1 = 10
, =>[6,3,1]
- Result 4:
3*3 + 1*1 = 10
, =>[3,3,3,1]
- ...
Example2: Assuming target = 20,
✅ Possible outcomes are as follows:
- Result 1:
18*1 + 2*1 = 20
, =>[18,1,1]
- Result 2:
12*1 + 8*1 = 20
, =>[12,8]
- ...
❌ Bad Result:
- 20 1s, against the rules: pick up to 10
- [1,2,5], the sum is not right
Note
- Pick a maximum of 10, a minimum of 1, repeatable picks
- if no suitable result is found, return
undefined
Solution
Solution1- Recursive computation - 10/25/2022
Recursion always solves this kind of problem, maybe there are other better ways, I will keep updating and trying.
TypeScript Playground - Recursive computation
Question
I want to find an optimal solution, speed first.
const list = [
1,
3,
6,
8,
12,
18,
25,
28,
30,
40,
45,
50,
60,
68,
78,
88,
98,
128,
158,
198,
248,
298,
348,
418,
488,
548,
588,
618,
648,
698,
798,
818,
848,
898,
998,
1048,
1098,
1148,
1198,
1248,
1298,
1398,
1448,
1498,
1598,
1648,
1998,
2298,
2598,
2998,
3298,
3998,
4498,
4998,
5898,
6498,
];
function getCombinations(
list: number[],
target: number
): Array<number> | undefined {
// TODO...
}