public class DiceSum {
int n = 3; // 骰子个数
int m = 6; // 骰子的最大点数
int[] properties = new int[m * n + 1]; // n颗骰子点数的和的次数 (用于解法1)
int[][] properties2 = new int[2][m * n + 1]; // n颗骰子点数的和的次数 (用于解法2)
int flag = 0; // 标记properties2取第一个数组还是第二个数组
/***
* 递归解法
*
* @param curNum
* 当前骰子序号
* @param sum
* 当前骰子点数综合
*/
public void method1(int curNum, int sum) {
if (curNum == n) {
for (int i = 1; i <= m; i++) {
properties[sum + i]++;
}
} else {
for (int i = 1; i <= m; i++) {
method1(curNum + 1, sum + i);
}
}
}
/***
* 利用循环求解
*/
public void metho2() {
for (int i = 0; i <= m; i++) {
this.properties2[flag][i] = 1;
}
for (int k = 2; k <= n; k++) {
flag = 1 - flag;
for (int i = 0; i <= m * n; i++)
this.properties2[flag][i] = 0;
for (int j = k; j <= k * m; j++) {
for (int i = 1; j - i > 0 && i <= m; i++) {
this.properties2[flag][j] += this.properties2[1 - flag][j
- i];
}
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
DiceSum ds = new DiceSum();
// ds.method1(1, 0);
ds.metho2();
for (int i = ds.n; i < ds.properties.length; i++) {
System.out.print(i + " ");
}
System.out.println();
for (int i = ds.n; i < ds.properties.length; i++) {
System.out.print(ds.properties2[ds.flag][i] + " ");
}
}
}