博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Algorithm] Dynamic programming: Find Sets Of Numbers That Add Up To 16
阅读量:5120 次
发布时间:2019-06-13

本文共 1789 字,大约阅读时间需要 5 分钟。

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)

转载于:https://www.cnblogs.com/Answer1215/p/10393635.html

你可能感兴趣的文章
树状数组_一维
查看>>
如果没有按照正常的先装iis后装.net的顺序,可以使用此命令重新注册一下:
查看>>
linux install ftp server
查看>>
嵌入式软件设计第8次实验报告
查看>>
算法和数据结构(三)
查看>>
Ubuntu下的eclipse安装subclipse遇到没有javahl的问题...(2天解决了)
查看>>
alter database databasename set single_user with rollback IMMEDIATE 不成功问题
查看>>
WCF揭秘——使用AJAX+WCF服务进行页面开发
查看>>
【题解】青蛙的约会
查看>>
IO流
查看>>
mybatis调用存储过程,获取返回的游标
查看>>
设计模式之装饰模式(结构型)
查看>>
面向对象的设计原则
查看>>
Swift3.0服务端开发(三) Mustache页面模板与日志记录
查看>>
【转】 FPGA设计的四种常用思想与技巧
查看>>
EntityFrameWork 实现实体类和DBContext分离在不同类库
查看>>
新手算法学习之路----二叉树(在一个二叉查找树中插入一个节点)
查看>>
autopep8
查看>>
GIT在Linux上的安装和使用简介
查看>>
基于C#编程语言的Mysql常用操作
查看>>