You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

28 lines
575 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package 01.mca_08_dp;
public class Code02_SumWays {
// arr中都是正数sum也是正数
// 求组成sum的方法数量
public static int sumWays(int[] arr, int sum) {
int n = arr.length;
if (n == 0) {
return sum == 0 ? 1 : 0;
}
int[][] dp = new int[n][sum + 1];
for (int i = 0; i < n; i++) {
dp[i][0] = 1;
}
if (arr[0] <= sum) {
dp[0][arr[0]] = 1;
}
for (int i = 1; i < n; i++) {
for (int j = 1; j <= sum; j++) {
dp[i][j] = dp[i - 1][j] + (j - arr[i] >= 0 ? dp[i - 1][j - arr[i]] : 0);
}
}
return dp[n - 1][sum];
}
}