code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

07 Combinations

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const combinations = (n, k) => {
  const result = []
  const backtrack = (index, curr) => {
    if (curr.length == k) {
      result.push(curr.slice())
      return
    }
    for (let i = index; i <= n; i++) {
      curr.push(i)
      backtrack(i + 1, curr)
      curr.pop()
    }
  }
  backtrack(1, [])
  return result
}

console.log(combinations(4, 2))

Created 2022-02-26T02:08:30+00:00 · Edit