【发布时间】:2017-08-16 16:54:31
【问题描述】:
我正在尝试解决,使用递归一种最大化子序列和的方法,使得没有三个元素是连续的。
有一种方法可以通过动态编程来做到这一点,但我想先使用递归来构建它。
一些示例输入和输出:
Input:{1, 2, 3}
Output: 5
Input:{100, 1000, 100, 1000, 1}
Output: 2101
Input:{1, 2, 3, 4, 5, 6, 7, 8}
Output: 27
除了第二个 {100, 1000, 100, 1000, 1} 之外,我能够得到大部分正确的结果。
我的解决方案:
int maxSubsequenceSum(vector<int> nums)
{
return helper(nums, nums.size());
}
int helper(vector<int>& nums, int index)
{
if (index <= 0) return 0;
int withoutThird = helper(nums, index - 3) + nums[index - 1] + nums[index - 2];
int withoutSecond = helper(nums, index - 3) + (index - 1 < 0 ? 0 : nums[index - 1]) + (index - 3 < 0 ? 0 : nums[index - 3]);
int withoutFirst = helper(nums, index - 3) + (index - 2 < 0 ? 0 : nums[index - 2]) + (index - 3 < 0 ? 0 : nums[index - 3]);
return max(withoutThird, max(withoutSecond, withoutFirst));
}
单独的三个 withoutThird、withoutSecond 和 withoutFirst 仅在递归排列失败时才给出正确的结果。为什么会失败,这是一种正确的递归方法吗?
【问题讨论】:
-
我可以指出的一个错误是您的代码不会考虑序列中的替代元素。这意味着如果最佳选择是选择替代元素,那么这将不起作用。因此,您可能想尝试基于最长递增子序列的递归实现行的另一种递归方法。