之前写得代码,比较有意思,现放出来。
public static void main(String[] args) {
final int n = 21;
int[] a = new int[6];
int count = 0;
for (int i = 1, p = 0, s = 0; ; i++, count++) {
a[p++] = i;
s += i;
if (s < n) {
continue;
}
if (s == n) {
for (int j = 0; j < p; j++) {
System.out.print(a[j] + "+");
}
System.out.println();
if(a[0] == 10) {//a[1] = 11, last hit.
break;
}
}
s -= a[--p];
s -= a[--p];
i = a[p];
}
System.out.println("loop:" + count);
}