Skip to content

Commit

Permalink
m416
Browse files Browse the repository at this point in the history
  • Loading branch information
chenzhengwei committed Feb 16, 2017
1 parent a0a413f commit c836257
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions Solution/401-450/416.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,45 @@ public class Solution {
return dp[len][target];
}
}
```
另外一个降低了空间复杂度的01背包方案
```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[target + 1];
Arrays.fill(dp, false);
dp[0] = true;
for (int i = 1; i < len + 1; i++) {
// 注意这里的方向是从后向前
for (int j = target; j > 0; j--) {
if (j >= nums[i - 1]) {
dp[j] = dp[j] || dp[j - nums[i - 1]];
}
}
}
return dp[target];
}
}
```

0 comments on commit c836257

Please sign in to comment.