all combinations Algorithm

The all combinations algorithm, also known as exhaustive search or brute force algorithm, is a problem-solving approach that generates all possible combinations of a given set of elements to find the optimal or desired solution. This algorithm is commonly used in solving combinatorial problems, such as permutations, combinations, and subsets. It works by systematically enumerating every possible combination and then checking if the generated combination satisfies the desired criteria or constraints of the problem. While the all combinations algorithm guarantees finding the correct solution, it can be highly inefficient, especially for large datasets, as the number of combinations grows exponentially with the number of elements. Despite its inefficiency, the all combinations algorithm can serve as a useful benchmark for comparing the performance of more sophisticated algorithms, as it establishes an upper bound on the solution space. This algorithm is also valuable in solving small-scale problems or problems with limited solution spaces, where it is more feasible to explore every possible combination. Additionally, the all combinations algorithm can be employed as a last resort when no other more efficient algorithm is available for a particular problem. However, in practice, more advanced techniques such as backtracking, dynamic programming, and heuristic search are usually employed to achieve more efficient problem-solving.
"""
        In this problem, we want to determine all possible combinations of k
        numbers out of 1 ... n. We use backtracking to solve this problem.
        Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!)))
"""


def generate_all_combinations(n: int, k: int) -> [[int]]:
    """
    >>> generate_all_combinations(n=4, k=2)
    [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
    """

    result = []
    create_all_state(1, n, k, [], result)
    return result


def create_all_state(increment, total_number, level, current_list, total_list):
    if level == 0:
        total_list.append(current_list[:])
        return

    for i in range(increment, total_number - level + 2):
        current_list.append(i)
        create_all_state(i + 1, total_number, level - 1, current_list, total_list)
        current_list.pop()


def print_all_state(total_list):
    for i in total_list:
        print(*i)


if __name__ == "__main__":
    n = 4
    k = 2
    total_list = generate_all_combinations(n, k)
    print_all_state(total_list)

LANGUAGE:

DARK MODE: