-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
chenzhengwei
committed
Feb 16, 2017
1 parent
33f5e82
commit a0a413f
Showing
2 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
#416. Partition Equal Subset Sum | ||
[题目链接](https://leetcode.com/problems/partition-equal-subset-sum/) | ||
```java | ||
public class Solution { | ||
/* | ||
转化为01背包问题 | ||
*/ | ||
public boolean canPartition(int[] nums) { | ||
// 首先判断一些特殊情况 | ||
int sum = 0; | ||
for (int i = 0; i < nums.length; i++) { | ||
sum += nums[i]; | ||
} | ||
if (sum % 2 == 1) { | ||
return false; | ||
} | ||
int target = sum / 2; | ||
for (int i = 0; i < nums.length; i++) { | ||
if (nums[i] > target) { | ||
return false; | ||
} else if (nums[i] == target) { | ||
return true; | ||
} | ||
} | ||
|
||
// 如果仍无法判断,转化为01背包问题 | ||
int len = nums.length; | ||
boolean[][] dp = new boolean[len + 1][target + 1]; | ||
for (int i = 0; i < dp.length; i++) { | ||
Arrays.fill(dp[i], false); | ||
} | ||
for (int i = 0; i < len + 1; i++) { | ||
dp[i][0] = true; | ||
} | ||
for (int i = 1; i < len + 1; i++) { | ||
for (int j = 1; j < target + 1; j++) { | ||
dp[i][j] = dp[i - 1][j]; | ||
if (j >= nums[i - 1]) { | ||
dp[i][j] = dp[i][j] || dp[i - 1][j - nums[i - 1]]; | ||
} | ||
} | ||
} | ||
return dp[len][target]; | ||
} | ||
} | ||
``` |