Elegant JS solution, 10 lines of code with nice formatting.


  • 0
    K

    Finally, found elegant JS solution. It wasn't easy to understand right index manipulations without paper and pen:

    var combine = function(n, k, buffer=[]) {
        let res = [];
    
        while (n >= k) {
            let newBuffer = buffer.concat(n--);
            
            if (k === 1) {
                res.push(newBuffer);
            } else {
                let combined = combine(n, k - 1, newBuffer);
                res = res.concat(combined);
            }
        }
    
        return res;
    };
    

    And for fun, for those who like the shortest code as possible :

    var combine = function(n, k, buffer=[]) {
        let res = [];
        for (; n >= k; n--)
            if (k === 1)  res.push(buffer.concat(n));
            else res = res.concat(combine(n - 1, k - 1, buffer.concat(n)));
        return res;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.