解题思路
通过第n个阶梯的花费为通过前两个阶梯中累计花费最小的那个并加上自身的花费,即cost(n) = min(cost(n-1), cost(n-2)) + cost
最终计算得出cost(last) = min(cost(last - 1), cost(last -2))
代码
-spec min_cost_climbing_stairs(Cost :: [integer()]) -> integer().
min_cost_climbing_stairs(Cost) ->
do_min_cost_climbing_stairs(Cost, _TotalCost = #{}, _Args = #{index => 1}).
do_min_cost_climbing_stairs([Cost | T], TotalCost, Args = #{index := Index}) ->
PreCost = maps:get(Index - 1, TotalCost, 0),
PrePreCost = maps:get(Index - 2, TotalCost, 0),
NewCost = min(PreCost, PrePreCost) + Cost,
do_min_cost_climbing_stairs(T, TotalCost#{Index => NewCost}, Args#{index := Index + 1});
do_min_cost_climbing_stairs(_, TotalCost, _Args = #{index := Index}) ->
PreCost = maps:get(Index - 1, TotalCost, 0),
PrePreCost = maps:get(Index - 2, TotalCost, 0),
min(PreCost, PrePreCost).