Teaching Kids Programming – Recursive Backtracking Algorithm to Compute the Combinations


Teaching Kids Programming: Videos on Data Structures and Algorithms

Given two integers n and k, return all possible combinations of k numbers out of 1 … n. You may return the answer in any order.

Example 1:
Input: n = 4, k = 2
Output:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

Example 2:
Input: n = 1, k = 1
Output: [[1]]

Compute the Combinations via Recursive Backtracking (Depth First Search)

There are tex_d3c4b91adc734191ced6678258b3b391 Teaching Kids Programming - Recursive Backtracking Algorithm to Compute the Combinations number of the combinations when you pick k items out of n. Therefore, the solution time complexity is tex_8a8d61e940878f62432a45107b4c7514 Teaching Kids Programming - Recursive Backtracking Algorithm to Compute the Combinations. We can backtracking with Depth First Search so that for each round, we can pick an item and DFS to next pick until we have k items.

This is similar to Permutations where each result can have K! different sequences: Teaching Kids Programming – Recursive Permutation Algorithm

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        def dfs(left, cur):
            if len(cur) == k:   # finish k items
                output.append(cur[:])
                return
            for i in range(left, n + 1):
                cur.append(i)   # pick i
                dfs(i + 1, cur) # pick next from i+1
                cur.pop()       # reset for next iteration
        output = []
        dfs(1, [])
        return output            

Permutations and Combinations

–EOF (The Ultimate Computing & Technology Blog) —

606 words
Last Post: Rolling Hash Algorithm to Find the Longest Prefix that Is a Suffix
Next Post: Algorithms to Compute the Interleaved Linked List

The Permanent URL is: Teaching Kids Programming – Recursive Backtracking Algorithm to Compute the Combinations (AMP Version)

Leave a Reply