问题描述

给定一个数组及数字 k ,从数组中找出所有相加结果为 k 的组合。

示例:

给定数组 [1,1,1]k=2,输出:

 [[1,1]]

给定数组 [10, 1, 2, 7, 6, 1, 5]k=8,输出:

 [ [ 1, 2, 5 ], [ 1, 7 ], [ 1, 1, 6 ], [ 2, 6 ] ]

分析

这里的思路是把 k 逐步拆解。既然要找出相加等于 k 的元素,那根据递归的思想,不难想到假如已经找到了数组中一个有效的元素,那么接下来就是从剩余的元素中继续去找,相加等于 k 减去该元素的那些组合,形成了一个新的子问题。

所以对于第一个结果的查找,可以从索引为 0 的位置开始遍历数组:

  • 从候选数据 arr 中取出第一个元素 item0,这样得到了一个取出该元素后的新数组 arr1
  • k 中减去该元素 item0 得到一个新的 k0
  • 如此往复,接下来任务就是需要在新的数组 arr1 中找出一个组合,其相加结果为 k0
  • 最后必然会进行到 k 为零的时候,此时将前面取出的数组合一起便得到了一个结果。
  • 如果数组都遍历完了,但 K 最终没有变成零,说明本次查找没有结果。

第二个结果:

  • 上面查找结束,开始从原数组中第二个位置开始重复上面的步骤。

...

直到进行到数组的最后一个元素。将前面得到的结果组合后返回。

实现

根据上面的分析得出如下的实现:

/**
* k-sum 实现,从候选数组中找出所有相加结果为 k 的组合
* @param {*} arr 候选数组
* @param {*} k 目标数字
*/
function ksum(arr, k) {
var result = []; function process(input, tmpK, tmpResult) {

tmpResult = tmpResult || [];

if (tmpK = 0 && tmpResult.length > 0) {

tmpResult.sort((a, b) => a - b);

var hasDuplicate = result.some(v => {

return v.join("") = tmpResult.join("");

});

if (!hasDuplicate) {

result.push(tmpResult);

}

} else if (tmpK > 0) {

for (let i = 0; i < input.length; i++) {

const num = input[i];

process(input.slice(i + 1), tmpK - num, tmpResult.concat(num));

}

}

}

process(arr, k);

return result;

}

测试:

console.log(ksum([1,1,1], 2));
// [ [ 1, 1 ] ] console.log(ksum([10, 1, 2, 7, 6, 1, 5], 8));

// [ [ 1, 2, 5 ], [ 1, 7 ], [ 1, 1, 6 ], [ 2, 6 ] ]

相关资源

k-sum 问题的更多相关文章

  1. summary of k Sum problem and solutions in leetcode

    I found summary of k Sum problem and solutions in leetcode on the Internet. http://www.sigmainfy.com ...

  2. lintcode: k Sum 解题报告

    K SUM My Submissions http://www.lintcode.com/en/problem/k-sum/ 题目来自九章算法 13% Accepted Given n distinc ...

  3. k Sum | & ||

    k Sum Given n distinct positive integers, integer k (k <= n) and a number target. Find k numbers ...

  4. 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)

    转自  http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...

  5. K Sum(2 Sum,3 Sum,4 Sum,3-Sum Closest)

    算是经典算法问题了.这里主要针对只存在一个解或者只需要求一个解的情况描述一下解题思路.若需要找到所有可能解,方法需要略作调整.如有问题,欢迎指正. 2 sum: 如果已排序,可直接用夹逼法,即两指针从 ...

  6. LeetCode解题报告--2Sum, 3Sum, 4Sum, K Sum求和问题总结

    前言: 这几天在做LeetCode 里面有2sum, 3sum(closest), 4sum等问题, 这类问题是典型的递归思路解题.该这类问题的关键在于,在进行求和求解前,要先排序Arrays.sor ...

  7. 2019年南京网络赛E题K Sum(莫比乌斯反演+杜教筛+欧拉降幂)

    目录 题目链接 思路 代码 题目链接 传送门 思路 首先我们将原式化简: \[ \begin{aligned} &\sum\limits_{l_1=1}^{n}\sum\limits_{l_2 ...

  8. 南京网络赛 E K Sum

    K Sum 终于过了这玩意啊啊啊==== 莫比乌斯反演,杜教筛,各种分块,积性函数怎么线性递推还很迷==,得继续研究研究 #include<bits/stdc++.h> using nam ...

  9. 2019南京网络赛E:K Sum

    Description: 定义函数 \[ f _n (k) = \sum _{l _1 = 1} ^n \sum _{l _2 = 1} ^n \cdots \sum _{l _k = 1} ^n \ ...

  10. Leetcode - K Sum

    List<List<Integer>> kSum_Trim(int[] a, int target, int k) { List<List<Integer>& ...

随机推荐

  1. 第九章 Servlet工作原理解析(待续)

    从 Servlet容器说起 创建 Servlet实例 Servlet体系结构 Servlet如何工作 Servlet中的Listener Filter如何工作 Servlet中的url-pattern

  2. Win10 蓝屏

    Win10  蓝屏 3分钟就蓝屏,显卡驱动的问题吗?无线网卡?USB?声卡.各种硬件驱动都有可能. KERNEL_SECURITY_CHECK_FAILURE DISM.exe/Online/Clea ...

  3. opencv相关

    http://opencv.org/ ================== 不错的博客: 图像处理(小魏的修行路):http://blog.csdn.net/xiaowei_cqu/article/c ...

  4. TCP/IP 笔记 7 Ping

    lenovo-myc@lenovomyc-Lenovo-Product:~$ ping www.baidu.com PING www.a.shifen.com (() bytes of data. 这 ...

  5. Reporting services

    “数据库引擎服务”可以承载报表服务器数据库.Reporting Services 需要SQL Server 2008 数据库引擎的本地或远程实例来承载报表服务器数据库.如果同时安装数据库引擎实例和 R ...

  6. nodejs的POST请求

    http://blog.csdn.net/puncha/article/details/9015317 Nodejs 发送HTTP POST请求实例 2013-06-03 17:55 71745人阅读 ...

  7. 【Java基础专题】编码与乱码(05)---GBK与UTF-8之间的转换

    原文出自:http://www.blogjava.net/pengpenglin/archive/2010/02/22/313669.html 在很多论坛.网上经常有网友问" 为什么我使用 ...

  8. Tensorflow梯度下降应用

    import tensorflow as tfimport numpy as np #使用numpy生成随机点x_data = np.random.rand(100)y_data = x_data*0 ...

  9. Tensorflow fetch和feed

    import tensorflow as tf #Fetch input1 = tf.constant(1.0)input2 = tf.constant(3.0)input3 = tf.constan ...

  10. Opencv Laplacian(拉普拉斯算子)

    #include <iostream>#include <opencv2/opencv.hpp>#include <math.h> using namespace ...