Old Top Coder riddle: Making a number by inserting +

后端 未结 6 1546
借酒劲吻你
借酒劲吻你 2021-02-06 05:41

I am thinking about this topcoder problem.

Given a string of digits, find the minimum number of additions required for the string to equal some target n

6条回答
  •  感情败类
    2021-02-06 05:51

    Seems to be too late .. but just read some comments and answers here which say no to dp approach . But it is a very straightforward dp similar to rod-cutting problem:

    To get the essence:

    int val[N][N];
    int dp[N][T];
    
    val[i][j]: numerical value of s[i..j] including both i and j
    
    val[i][j] can be easily computed using dynamic programming approach in O(N^2) time
    
    dp[i][j] : Minimum no of '+' symbols to be inserted in s[0..i] to get the required sum j
    
    dp[i][j] = min( 1+dp[k][j-val[k+1][j]] ) over all k such that 0<=k<=i and val[k][j]>0
    

    In simple terms , to compute dp[i][j] you assume the position k of last '+' symbol and then recur for s[0..k]

提交回复
热议问题