115. Distinct Subsequences
# Hard 太难了
Two-sequence DP problem. It's easy to define distinct[i][j],
which means how many distinct ways from s[:i] to t[:j]
. But how to compute distinct[i][j]
according to distinct[i-1[j], distinct[i][j-1]
and distinct[i-1][j-1]
is difficult to have an idea.
Solution:
Initilize
distinct[i][j]
, set empty row and column.distinct[0][0]=1
, froms[i]
toNULL
is 1, fromNULL
tot[j]
is 0.If
s[i] = t[j]
, thendistinct[i][j]=distinct[i-1][j-1]+distinct[i-1][j]
, think this with drawing.If
s[i] != t[j]
, thendistinct[i][j]=distinct[i-1][j-1]
.Return
distinct[len(s)][len(t)]
.
distinct[i][j]
与distinct[i][j-1]
没有任何关系。
这种题最重要的思维是找二维数组distinct[i][j]
与前面的 distinct[i-1][j], distinct[i][j-1], disintct[i][j]
中的谁有直接关系,并且有什么逻辑联系。
Last updated
Was this helpful?