Skip to content
陈广亮的技术博客
Go back

JS 实现排列组合数组

首先介绍个网站 codewars 一个编码社区,做题升级跟玩游戏一样,在获得乐趣的同时还能得到很大的提升。

题目:写一个方法输出所有的可能的子数组,就是排列组合了

power([1, 2, 3]); // => [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

大神的代码:

function power(s) {
  return s.reduce(function (p, e) {
    return p.concat(
      p.map(function (sub) {
        return sub.concat([e]);
      })
    );
  }, [[]]);
}

每次循环取源数组一个数,对结果数组(初始化 [[]])的每个子项做 concat,并添加到结果数组中:

[[]]
[[], [1]]
[[], [1], [2], [1,2]]
[[], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3]]

Share this post on:

Previous Post
JS repeat 方法的演变历史