Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b1c3d5c

Browse files
添加了二维数组版本,相比于一维好理解
1 parent 653d645 commit b1c3d5c

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎problems/0416.分割等和子集.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,45 @@ class Solution {
210210
}
211211
```
212212

213+
二维数组版本(易于理解):
214+
```Java
215+
class Solution {
216+
public boolean canPartition(int[] nums) {
217+
int sum = 0;
218+
for (int i = 0; i < nums.length; i++) {
219+
sum += nums[i];
220+
}
221+
222+
if (sum % 2 == 1)
223+
return false;
224+
int target = sum / 2;
225+
226+
//dp[i][j]代表可装物品为0-i,背包容量为j的情况下,背包内容量的最大价值
227+
int[][] dp = new int[nums.length][target + 1];
228+
229+
//初始化,dp[0][j]的最大价值nums[0](if j > weight[i])
230+
//dp[i][0]均为0,不用初始化
231+
for (int j = nums[0]; j <= target; j++) {
232+
dp[0][j] = nums[0];
233+
}
234+
235+
//遍历物品,遍历背包
236+
//递推公式:
237+
for (int i = 1; i < nums.length; i++) {
238+
for (int j = 0; j <= target; j++) {
239+
//背包容量可以容纳nums[i]
240+
if (j >= nums[i]) {
241+
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - nums[i]] + nums[i]);
242+
} else {
243+
dp[i][j] = dp[i - 1][j];
244+
}
245+
}
246+
}
247+
248+
return dp[nums.length - 1][target] == target;
249+
}
250+
}
251+
```
213252
Python:
214253
```python
215254
class Solution:

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /