题解:
链接:https://leetcode-cn.com/problems/split-array-largest-sum/
下面这种情况是dfs是超时的,有时间加一下记忆化
class Solution {
public:
int splitArray(vector<int>& nums, int m) {
int n = nums.size();
vector<vector<long long>> f(n + 1, vector<long long>(m + 1, LLONG_MAX));
vector<long long> sub(n + 1, 0);
for (int i = 0; i < n; i++) {
sub[i + 1] = sub[i] + nums[i];
}
f[0][0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= min(i, m); j++) {
for (int k = 0; k < i; k++) {
f[i][j] = min(f[i][j], max(f[k][j - 1], sub[i] - sub[k]));
}
}
}
return (int)f[n][m];
}
};
class Solution {
public:
int splitArray(vector<int>& nums, int m) {
if(nums.size() <= 0) {
return 0;
}
int begin = 0;
int step = m;
int min_sum = INT_MAX;
// 后缀数组和
vector<long> prefix_sum(nums.size(), 0);
prefix_sum[nums.size()-1] = nums[nums.size()-1];
if(nums.size() >= 2) {
for(int i = nums.size()-2; i >= 0; --i) {
if(prefix_sum[i] == INT_MAX || nums[i] == INT_MAX) {
prefix_sum[i] = INT_MAX;
} else {
prefix_sum[i] = nums[i] + prefix_sum[i+1];
}
}
}
vector<int> path;
dfs(nums, path, begin, step, min_sum, prefix_sum);
return min_sum;
}
void dfs(vector<int>& nums, vector<int>& path, int begin, int step, int& min_sum
, vector<long>& prefix_sum) {
if(begin == nums.size()) {
return;
}
if(step == 1) {
path.push_back(prefix_sum[begin]);
// 取出这种分割情况下的最大值
auto max_ite = max_element(path.begin(), path.end());
int max_value = *max_ite;
// 判断最小值
min_sum = min(min_sum, max_value);
path.pop_back();
return;
}
int temp_sum = 0;
for(int i = begin; i < nums.size(); ++i) {
if(temp_sum == INT_MAX || nums[i] == INT_MAX) {
temp_sum = INT_MAX;
} else {
temp_sum += nums[i];
}
path.push_back(temp_sum);
dfs(nums, path, i+1, step-1, min_sum, prefix_sum);
path.pop_back();
}
}
};