Search and backtracking · 8 / 15 Exercise Medium

Combinations

Objective

Create a Python program that generates all the combinations of k numbers chosen from 1 to n, regardless of order. To avoid repeats, each number is always chosen greater than the previous one.

Instructions

  • Read one line with two integers n and k, with 1 ≤ k ≤ n ≤ 7.
  • Write a recursive function combinations(n, k, start, current, result) that receives the number from which choosing can start. At each step it tries the values from start to n, adds them, calls the function with v + 1 and removes them when coming back.
  • Show each combination on a line, with the numbers separated by spaces, in the order they are generated, and finish with Total: t.
Input
4 2
Output
1 2
1 3
1 4
2 3
2 4
3 4
Total: 6

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise