[Algorithm] Dynamic programming: Find Sets Of Numbers That Add Up To 16
For a given array, we try to find set of pair which sums up as the given target number.
For example, we are given the array and target as:
const data = [2, 4, 6, 10]; const target = 16;
We should be able to find 2 pair, which sum up to 16:
{2,4,10} {6,10}
We need to create a function to return the number of pair we found, in this case, the answer is: 2
const data = [2, 4, 6, 10]; /** * Return number of pair found */ function DP(data, target = 16) { let memo = {}; return rc(data, target, data.length - 1, memo); function rc(data, target, i, memo) { // Construct the key - value for memo let key = `${target}-${i}`; // Store the result let res = 0; // return the value if already calcualte if (memo[key]) { return memo[key]; } // if the target is zero, then it is empty set, return 1 if (target === 0) { return 1; } else if (target < 0) { // if target < 0, we don't consider the case, return 0 return 0; } else if (i < 0) { // if i <0, means we run out of element, return 0 return 0; } // if current value is larger than targer, we continue with next value if (data[i] > target) { res = rc(data, target, i - 1, memo); } else { /** * Two cases: * 1. The current value is not include: * rc(data, target, i - 1, memo) * 2. The current value is include: the rest of els should sum up to new target value * rc(data, target - data[i], i - 1, memo) */ // i is not included + i is included res = rc(data, target, i - 1, memo) + rc(data, target - data[i], i - 1, memo); } memo[key] = res; return res; } } console.log(DP(data, 16)); // 2
Time complexity: O(target * n * 2 + 1) = O(T*N)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具