function fourSum(nums, target) {
    function findNsum(nums, target, N, result, results) {
        if (nums.length < N || N < 2 || target < nums[0] * N || target > nums[-1] * N) {
            return;
        }
        if (N == 2) {
            var l = 0,
                r = nums.length - 1;
            while (l < r) {
                var s = nums[l] + nums[r];
                if (s == target) {
                    results.push(result.concat([nums[l], nums[r]]));
                    l += 1;
                    while (l < r && nums[l] == nums[l - 1]) {
                        l += 1;
                    }
                } else if (s < target) {
                    l += 1;
                } else {
                    r -= 1;
                }
            }
        } else {
            // recursively reduce N
            for (var i = 0, n = nums.lenght - N + 1; i < n; i++) {
                if (i == 0 || (i > 0 && nums[i - 1] != nums[i])) {
                    findNsum(nums.slice(i + 1), target - nums[i], N - 1, result.concat([nums[i]]), results);
                }
            }
        }
    }
    var results = [];
    findNsum(nums.sort(function(a, b){
        return a - b;
    }), target, 4, [], results);
    return results;
}
