DataStructure_Algorithm_HandBook_PreForLeetCode

77. Combinations

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

You may return the answer in any order.

Example 1:

Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.

Example 2:

Input: n = 1, k = 1
Output: [[1]]
Explanation: There is 1 choose 1 = 1 total combination.

Constraints:

solution

首先这里需要返回长度为 k 的所有组合

注意,在JavaScript中,函数内部并不能直接访问外部的变量,而是需要通过参数传递或者通过闭包的方式来访问外部变量。

var combine = function(n, k) {
    let result = [];
    dfs(1, [], n, k, result);
    return result;
};

function dfs(index, path, n, k, result) {
    if (path.length === k) {
        //因为数组是引用类型,直接添加的话只是添加了对 path 数组的引用,而不是数组的副本。
        //这样的话,当 path 数组后续发生变化时,添加到 result 数组中的元素也会发生变化,可能会造成错误的结果
        //可以使用扩展运算符 ... 来复制数组,确保向 result 数组添加的是 path 数组的副本 
        result.push([...path]); // 将当前组合添加到结果中
        return;
    }
    for (let i = index; i <= n; i++) {
        path.push(i); // 将当前数字添加到组合中
        dfs(i + 1, path, n, k, result); // 递归构建下一个数字的组合
        path.pop(); // 回溯,移除最后一个数字,尝试其他可能的组合
    }
}

但是如果数据规模很大,可能就过不了了,这里可以剪枝优化一下,避免无效的递归。 这里如果剩下的数字 加上 已经选的数字 小于需要的数字,就没有必要继续递归了。

var combine = function(n, k) {
    let result = [];
    dfs(1, [], n, k, result);
    return result;
};

function dfs(index, path, n, k, result) {
    if (path.length === k) {
        //因为数组是引用类型,直接添加的话只是添加了对 path 数组的引用,而不是数组的副本。
        //这样的话,当 path 数组后续发生变化时,添加到 result 数组中的元素也会发生变化,可能会造成错误的结果
        //可以使用扩展运算符 ... 来复制数组,确保向 result 数组添加的是 path 数组的副本 
        result.push([...path]); // 将当前组合添加到结果中
        return;
    }
    for (let i = index; i <= n; i++) {
        //剪枝,不可能有 k 个数
        if(path.length + n - i +1 < k ) return;
        path.push(i); // 将当前数字添加到组合中
        dfs(i + 1, path, n, k, result); // 递归构建下一个数字的组合
        path.pop(); // 回溯,移除最后一个数字,尝试其他可能的组合
    }
}