算法练习(11) —— Split Array Largest Sum

来源:互联网 发布:vb中left是什么意思 编辑:程序博客网 时间:2024/05/20 05:57

算法练习(11) —— Split Array Largest Sum

习题

本题取自 leetcode 中的 Dynamic Programming 栏目中的第410题:
Split Array Largest Sum


题目如下:

Description:

Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.

Example:

Input:
nums = [7,2,5,10,8]
m = 2

Output:
18

Explanation:
There are four ways to split nums into two subarrays.
The best way is to split it into [7,2,5] and [10,8],
where the largest sum among the two subarrays is only 18.

Note

If n is the length of array, assume the following constraints are satisfied:

  • 1 ≤ n ≤ 1000
  • 1 ≤ m ≤ min(50, n)

思路与代码

  • 先理解一下题意,这次的有点绕: 给你两个输入,一个是整数数组nums,另一个是m。将nums分成m个小数组后,求出每个小数组内所有数的和,再在所有和中找到最大值res,作为输出。题目要让我们找到res的最小值。
  • 注意几个点:第一是数组内数字的顺序不能改变,第二是子数组不能为空,至少要有一个数据。
  • 思路的话,很容易就想到动态规划去了,毕竟这种类型的题目很适合动态规划。具体的状态转移方程为:
    // dp[a][b] : a为当前数组的长度, b为剩余切割的次数    // Xi为切割点    dp[len][m] = min {max(dp[Xi][m-1], dp[len-Xi][m-1])}    dp[1][m] = 1    dp[len][0] = len
  • 自己当时图方便用递归写的,写的挺粗,感觉运行速度有点慢。可以作以下改进:一是记录dp表,如果递归的时候能找到非0值就可以直接返回;二是将递归化为非递归

具体代码如下:

#include <iostream>#include <vector>using namespace std;class Solution {public:    int split(vector<int>& nums, int m) {        int len = nums.size();        if (len == 1)            return nums[0];        /*if (len == 2 && m == 1)            return nums[0] > nums[1] ? nums[0] : nums[1];*/        if (m == 0) {            int res = 0;            for (int i = 0; i < len; i++)                res += nums[i];            return res;        }        long long result = 9999999999;        for (int i = 1; i < len; i++) {            vector<int> left;            vector<int> right;            for (int j = 0; j < i; j++)                left.push_back(nums[j]);            for (int k = i; k < len; k++)                right.push_back(nums[k]);            for (int leftm = 0; leftm <= m - 1; leftm++) {                int rightm = m - 1 - leftm;                int l = split(left, leftm);                int r = split(right, rightm);                int sum = l > r ? l : r;                result = (result < sum) ? result : sum;            }        }        return result;    }    int splitArray(vector<int>& nums, int m) {        return split(nums, m - 1);    }};