gpt4 book ai didi

java - 这个算法使用DP吗?

转载 作者:行者123 更新时间:2023-12-05 08:20:04 27 4
gpt4 key购买 nike

所以我最近一直在学习动态规划 (DP),当我遇到以下问题时,我决定使用 DP,但由于我是算法初学者,我不确定这是否是 DP 的有效示例还是不是。

问题:

Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums.

Example 1:

Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

这是我的“DP”解决方案:

class Solution {
public int[] runningSum(int[] nums) {
int[] arr = new int[nums.length];

int sum = 0;

for(int i = 0; i < nums.length; i++){
arr[i] = nums[i] + sum;
sum += nums[i];
}

return arr;
}
}

最佳答案

根据 Wikipedia :

There are two key attributes that a problem must have in order for dynamic programming to be applicable: optimal substructure and overlapping sub-problems. If a problem can be solved by combining optimal solutions to non-overlapping sub-problems, the strategy is called "divide and conquer" instead. This is why merge sort and quick sort are not classified as dynamic programming problems.

在您的例子中,您正在实现以下策略:

  sum_all(array) = array[0] + sum_all(array[1..])

在每一步只有一个子问题,这意味着子问题没有重叠。实际上,这是分而治之的退化形式。

关于java - 这个算法使用DP吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62812522/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com