46. 携带研究材料
题目链接:题目页面 (kamacoder.com)
二维dp数组:
import java.util.*;
public class Main{public static void main(String[] args) {Scanner sc = new Scanner(System.in);int m = sc.nextInt();int n = sc.nextInt();int[] space = new int[m];int[] value = new int[m];for(int i = 0; i < m; ++i) {space[i] = sc.nextInt();} for(int i = 0; i < m; ++i) {value[i] = sc.nextInt();}int[][] dp = new int[m][n+1];for(int i = 0; i < m; ++i) {dp[i][0] = 0;}for(int i = 0; i < n+1; ++i) {dp[0][i] = i >= space[0] ? value[0] : 0;}for(int i = 1; i < m; ++i) {for(int j = 1; j < n+1; ++j) {dp[i][j] = j >= space[i] ? Math.max(dp[i-1][j], dp[i-1][j-space[i]] + value[i]) : dp[i-1][j];}}System.out.println(dp[m-1][n]);}
}
一维dp数组:
import java.util.*;
public class Main{public static void main(String[] args) {Scanner sc = new Scanner(System.in);int m = sc.nextInt();int n = sc.nextInt();int[] space = new int[m];int[] value = new int[m];for(int i = 0; i < m; ++i) {space[i] = sc.nextInt();} for(int i = 0; i < m; ++i) {value[i] = sc.nextInt();}int[] dp = new int[n + 1];for(int i = 0; i < m; ++i) {for(int j = n; j >= 0; --j) {dp[j] = j < space[i] ? dp[j] : Math.max(dp[j], dp[j-space[i]] + value[i]); }}System.out.println(dp[n]);}
}
416. 分割等和子集
题目链接:416. 分割等和子集 - 力扣(LeetCode)
class Solution {public boolean canPartition(int[] nums) {int sum = 0, max = 0;for(int i = 0; i < nums.length; ++i) {sum += nums[i];max = max > nums[i] ? max : nums[i];}if(sum % 2 == 1 || max > sum/2) {return false;}boolean[] dp = new boolean[sum/2+1];dp[0] = true;for(int i = 0; i < nums.length; ++i) {for(int j = sum/2; j >= nums[i]; --j) {if(j >= nums[i]) {dp[j] |= dp[j-nums[i]];}}if(dp[sum/2] == true) {return true;}}return dp[sum/2];}
}