Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

77. Combinations #319

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

77. Combinations

给定两个整数 nk,返回 1 ... n 中所有可能的 k 个数的组合。

Example 1

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

Example 2

Input: n = 1, k = 1
Output: [[1]]

Constraints

Tcdian commented 4 years ago

Solution

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

    function backtracking(num) {
        if (combination.length === k) {
            result.push([...combination]);
            return;
        }
        if (num > n) {
            return;
        }
        combination.push(num);
        backtracking(num + 1);
        combination.pop();
        backtracking(num + 1);
    }
};
function combine(n: number, k: number): number[][] {
    const result: number[][] = [];
    const combination: number[] = [];
    backtracking(1);
    return result;

    function backtracking(num: number) {
        if (combination.length === k) {
            result.push([...combination]);
            return;
        }
        if (num > n) {
            return;
        }
        combination.push(num);
        backtracking(num + 1);
        combination.pop();
        backtracking(num + 1);
    }
};