赞
踩
初始化都默认为零即可。
- class Solution {
- public int lastStoneWeightII(int[] stones) {
- int sum = 0;
- for (int i = 0; i < stones.length; i++) {
- sum += stones[i];
- }
- int weight = sum / 2;
- int[] dp = new int[weight + 1];
- for (int i = 0; i < stones.length; i++) {
- for (int j = weight; j >= stones[i]; j--) {
- dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]);
- }
- }
- return (sum - dp[weight] * 2);
- }
- }
这道题转化为01背包问题的思路可以自行思考或者参照题解。
代码如下:
- class Solution {
- public int findTargetSumWays(int[] nums, int target) {
- int sum = 0;
- for (int i = 0; i < nums.length; i++) {
- sum += nums[i];
- }
- sum += target;
- if (sum < 0) return 0;
- if (sum % 2 == 1) return 0;
- sum /= 2;
- int[] dp = new int[sum + 1];
- dp[0] = 1;
- for (int i = 0; i < nums.length; i++) {
- for (int j = sum; j >= nums[i]; j--) {
- dp[j] += dp[j - nums[i]];
- }
- }
- return dp[sum];
- }
- }
这题和上面差不多,还是用的01背包问题,而且要更明显一些。
代码如下:
- class Solution {
- public int findMaxForm(String[] strs, int m, int n) {
- int[] n0 = new int[strs.length];
- int[] n1 = new int[strs.length];
- for (int i = 0; i < strs.length; i++) {
- for (int j = 0; j < strs[i].length(); j++) {
- if (strs[i].charAt(j) == '0') n0[i]++;
- else n1[i]++;
- }
- }
- int[][] dp = new int[m + 1][n + 1];
- for (int i = 0; i < strs.length; i++) {
- for (int j = m; j >= n0[i]; j--) {
- for (int k = n; k >= n1[i]; k--) {
- dp[j][k] = Math.max(dp[j][k], dp[j - n0[i]][k - n1[i]] + 1);
- }
- }
- }
- return dp[m][n];
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。