GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #77 - Combinations - LeetCode JavaScript Solutions

Back to all solutions

#77 - Combinations

Medium • View on LeetCode • View on GitHub
Backtracking

Problem Description

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

You may return the answer in any order.

Solution

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

function backtrack(result, n, k, combination = [], offset = 1) {
  if (combination.length === k) {
    result.push(combination);
  } else {
    while (offset <= n) {
      backtrack(result, n, k, [...combination, offset], ++offset);
    }
  }
}
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.