77. Combinations


Problem

https://leetcode.com/problems/combinations/

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example, If n = 4 and k = 2, a solution is:

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

Solution

Simple DFS

/**
 * @param {number} n
 * @param {number} k
 * @return {number[][]}
 */
var combine = function(n, k) {
    let result = []

    function combineHelper(res, i, n, k) {
        if (res.length === k) {
            result.push(res.slice())
            return
        }

        for (; i <= n; i += 1) {
            // speed up by checking if there are enought unused numbers
            if (n - i + 1 >= k - res.length) {
                res.push(i)
                combineHelper(res, i+1, n, k)
                res.pop()
            }
        }
    }

    combineHelper([], 1, n, k)

    return result
};

results matching ""

    No results matching ""