Skip to content

Commit

Permalink
a416
Browse files Browse the repository at this point in the history
  • Loading branch information
chenzhengwei committed Feb 16, 2017
1 parent 33f5e82 commit a0a413f
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,5 @@ leetcode 题解

[383. Ransom Note](Solution/351-400/383.md)

[416. Partition Equal Subset Sum](Solution/401-450/416.md)

46 changes: 46 additions & 0 deletions Solution/401-450/416.md
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];
}
}
```

0 comments on commit a0a413f

Please sign in to comment.