2017-05-08 81 views

回答

0

我想通過使用dynamic programming來解決這個問題。

下面是一些僞代碼,讓你開始:

Procedure num_solutions(n, k, m): 
    # Initialize memoization cache: 
    if this function has been called for the first time: 
    initialize memo_cache with (n+1)*(k+1)*(m+1) elements, all set to -1 

    # Return cached solution if available 
    if memo_cache[n][k][m] is not -1: 
    return memo_cache[n][k][m] 

    # Edge case: 
    if m is equal to 1: 
    # Solution only exists if 1 <= m <= k 
    if n >= 1 and n <= k, set memo_cache[n][k][m] to 1 and return 1 
    otherwise set memo_cache[n][k][m] to 0 and return 0 

    # Degenerate case: No solution possible if n<m or n>k*m 
    if n < m or n > k * m: 
    set memo_cache[n][k][m] to 0 and return 0 

    # Call recursively for a solution with m-1 elements 
    set sum to 0 
    for all i in range 1..k: 
    sum = sum + num_solutions(n - i, k, m - 1) 

    set memo_cache[n][k][m] to sum and return sum