Number of Sets of K Non-Overlapping Line Segments — LeetCode 1621 Python Solution
- Problem
- #1621
- Pattern
- Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates.
Example
- Input
- n = 4, k = 2
- Output
- 5
- Explanation
- The two line segments are shown in red and blue.
Python solution
class Solution:
def numberOfSets(self, n: int, k: int) -> int:
mod = 10**9 + 7
f = [[0] * (k + 1) for _ in range(n + 1)]
g = [[0] * (k + 1) for _ in range(n + 1)]
f[1][0] = 1
for i in range(2, n + 1):
for j in range(k + 1):
f[i][j] = (f[i - 1][j] + g[i - 1][j]) % mod
g[i][j] = g[i - 1][j]
if j:
g[i][j] += f[i - 1][j - 1]
g[i][j] %= mod
g[i][j] += g[i - 1][j - 1]
g[i][j] %= mod
return (f[-1][-1] + g[-1][-1]) % modComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1621. Number of Sets of K Non-Overlapping Line Segments is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1621. Number of Sets of K Non-Overlapping Line Segments?
- LeetCode 1621. Number of Sets of K Non-Overlapping Line Segments is rated Medium on LeetCode.
- What topics does LeetCode 1621. Number of Sets of K Non-Overlapping Line Segments cover?
- LeetCode 1621. Number of Sets of K Non-Overlapping Line Segments is tagged Math, Dynamic Programming and Combinatorics on LeetCode.