Two-dimensional Dynamic Programming
143 / 170Two-dimensional Dynamic ProgrammingLesson 8 of 11About 80 min
The same table as before, with transitions that need real care about what each branch means.
This counts appearances but initializes the whole table to zeros without setting the empty-target column. Type the two values it prints.
def appearances_broken(source, target): ways = [[0] * (len(target) + 1) for _ in range(len(source) + 1)] for i in range(1, len(source) + 1): for j in range(1, len(target) + 1): ways[i][j] = ways[i - 1][j] if source[i - 1] == target[j - 1]: ways[i][j] += ways[i - 1][j - 1] return ways[len(source)][len(target)] def appearances(source, target): ways = [[0] * (len(target) + 1) for _ in range(len(source) + 1)] for i in range(len(source) + 1): ways[i][0] = 1 for i in range(1, len(source) + 1): for j in range(1, len(target) + 1): ways[i][j] = ways[i - 1][j] if source[i - 1] == target[j - 1]: ways[i][j] += ways[i - 1][j - 1] return ways[len(source)][len(target)] print(appearances_broken("rabbbit", "rabbit"), appearances("rabbbit", "rabbit"))Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.