输入为两行:
第一行为两个正整数n(1 ≤ n ≤ 1000),sum(1 ≤ sum ≤ 1000)
第二行为n个正整数A[i](32位整数),以空格隔开。
输出所求的方案数
5 15 5 5 10 2 3
4
1 import java.util.Scanner; 2 3 /** 4 * @author Dell 5 * 6 */ 7 public class Main { 8 static public long dp[][]; 9 public static void main(String[] args) { 10 Scanner sc = new Scanner(System.in); 11 int n = sc.nextInt(); 12 int sum = sc.nextInt(); 13 int [] p = new int[(int) (n+1)]; 14 /** 15 * 循环全部从1开始 16 * 17 */ 18 for (int i= 1; i < p.length; i++) { 19 p[i] = sc.nextInt(); 20 } 21 dp = new long[n+1][sum+1]; 22 for (int i = 0; i <n+1; i++) { 23 for (int j = 0; j <sum+1; j++) { 24 dp[i][j] = 0; 25 } 26 } 27 dp[0][0] = 1; //初始化 0 行 28 for (int i = 1; i <=n; i++) { 29 for (int j = 0; j <=sum; j++) { // 0-sum列 30 long k; 31 if (j-p[i]<0) { 32 k = 0; 33 }else { 34 k = dp[i-1][j-p[i]]; 35 } 36 dp[i][j] = dp[i-1][j]+k; 37 } 38 } 39 System.out.println(dp[n][sum]); 40 } 41 }
原文:https://www.cnblogs.com/the-wang/p/8981278.html