[CodeForces] C. Python Indentation

Problem Link

 

Dp[i][j]: the number of possible ways from s[0, i] with the ith statement ending with indentation j. 

dp[0][0] = 1, the 1st statement must start with indentation 0.

Answer: sum of dp[n - 1][0 ~ (n - 1)]

 

State transition: 

1. if the previous statement is a for loop statement, then the current statement must have previous statement's indentation + 1, dp[i][j] = dp[i - 1][j - 1].

2. if the previous statement is a simple statement, for a fixed indentation k, the current statement can have indentation from 0 to k, it can not have indentation > k.

So for dp[i][j], we need to sum all dp[i - 1][k] such that k >= j (if k < j, then dp[i - 1][k] can not yield an identation level of j for the ith statement).

dp[i][j] = sum of dp[i - 1][j ~ (n - 1)], use prefix sum to optimize from O(N^3) to O(N^2).

 

 

 

posted @ 2022-02-07 23:04  Review->Improve  阅读(59)  评论(0编辑  收藏  举报