ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

PO65最后的士兵

2021-09-15 05:31:05  阅读:19  来源: 互联网

标签:temp nums int sum 最后 PO65 vector 士兵 include


image
image

思路:动态规划

#include <vector>
#include <numeric>
using namespace std;

class Solution
{
public:
    int lastStoneWeightII(vector<int> &nums)
    {
        int sum = accumulate(nums.begin(), nums.end(), 0);
        int n = nums.size(), m = sum / 2;
        vector<vector<int> > dp(n + 1, vector<int>(m + 1));
        dp[0][0] = true;
        for (int i = 0; i < n; ++i)
        {
            for (int j = 0; j <= m; ++j)
            {
                if (j < nums[i])
                {
                    dp[i + 1][j] = dp[i][j];
                }
                else
                {
                    dp[i + 1][j] = dp[i][j] || dp[i][j - nums[i]];
                }
            }
        }
        for (int j = m;; --j)
        {
            if (dp[n][j])
            {
                return sum - 2 * j;
            }
        }
    }
};

int main()
{
    Solution solution;
    vector<int>nums;
    int n, temp;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> temp;
        nums.push_back(temp);
    }
    cout << solution.lastStoneWeightII(nums) << endl;
    return 0;
}

-[1]最后一块石头的重量 II

标签:temp,nums,int,sum,最后,PO65,vector,士兵,include
来源: https://www.cnblogs.com/aoke2002/p/15270535.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有