Given a list[] of non-negative integers and a value sum, check if there is a subset of the given list whose sum is equal to the given number.
Building upon understanding of Subset sum (Memoization). Pay attention to the cache. Tabulation essentially reconstructs the cache.
Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.
The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.
def check(ls, total): cache = [[False] * (total + 1) for _ in range(len(ls) + 1)] for i in range(len(ls) + 1): cache[i][0] = True for i in range(1, len(ls) + 1): for j in range(1, total + 1): if j < ls[i - 1]: cache[i][j] = cache[i - 1][j] else: cache[i][j] = cache[i - 1][j] or cache[i - 1][j - ls[i - 1]] return cache[len(ls)][total] ls = [3, 34, 4, 12, 5, 2] total = 9 print(check(ls, total))
function check(list, total) { const cache = Array.from(Array(list.length + 1), () => Array(total + 1).fill(false)); for (let i = 0; i < list.length + 1; i++) { cache[i][0] = true; } for (let i = 1; i < list.length + 1; i++) { for (let j = 1; j < total + 1; j++) { if (j < list[i - 1]) { cache[i][j] = cache[i - 1][j]; } else { cache[i][j] = cache[i - 1][j] || cache[i - 1][j - list[i - 1]]; } } } return cache[list.length][total]; } const list = [3, 34, 4, 12, 5, 2]; const sum = 9; console.log(check(list, sum));