Skip to content
RSS feed tkhwang on GitHub tkhwang on Twitter

Combinations in javascript

πŸ’‘ General theory

          n!
nCr =  ----------
        r! (n-r)!

        n (n - 1)
nC2 =  ----------
           2

πŸ”₯ Combinations

const combinations = (array, length = array.length) => {
  const res = [];

  const dfs = (cur, start) => {
    if (cur.length === length) {
      res.push([...cur]);
      return;
    }

    for (let i = start; i < array.length; i += 1) {
      cur.push(array[i]);
      dfs(cur, i + 1);
      cur.pop();
    }
  };

  dfs([], 0);

  return res;
};

const nums = [1, 2, 3, 4, 5];
const result = combinations(nums, 2);
/*
0: (2) [1, 2]
1: (2) [1, 3]
2: (2) [1, 4]
3: (2) [1, 5]
4: (2) [2, 3]
5: (2) [2, 4]
6: (2) [2, 5]
7: (2) [3, 4]
8: (2) [3, 5]
9: (2) [4, 5]
*/

πŸ—’οΈ Typical problems