搜狐笔试第二题

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<algorithm>

int main()
{
    int len = 0;
    scanf("%d", &len);
    std::vector<int> nums(len, 0);
    for (int i = 0; i < len; ++i)
    {
        scanf("%d", &nums[i]);
    }

    std::vector<std::vector<int>> dp(len, std::vector<int>(len, std::numeric_limits<int>::max()));

    for (int i = 0; i < len; ++i)
    {
        dp[i][i] = 0;
    }

    int result = 0;
    for (int i = 0; i < len; ++i)
    {
        result += nums[i];
    }

    for (int i = 1; i < len; ++i)
    {
        for (int start = 0; start + i < len; ++start)
        {
            int end = start + i;
            if (nums[start] == nums[end])
            {
                dp[start][end] = std::min(dp[start][end], i <= 1 ? 0 : dp[start + 1][end - 1]);
            }
            dp[start][end] = std::min(dp[start][end], std::min(dp[start + 1][end] + nums[start], dp[start][end - 1] + nums[end]));
        }
    }

    result += dp[0][len - 1];

    printf("%d\n", result);

    system("pause");
    return 0;
}

经典DP,修改字符串增加最少字符为回文字符串的状态转换表达式即可,
全部评论
大佬可以大致解释下不
点赞 回复 分享
发布于 2017-09-17 22:43

相关推荐

程序员猪皮:看不到八股什么意思
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务