题目描述
任何一个大于1的自然数n,总可以拆分成若干个小于n的自然数之和。现在给你一个自然数n,要求你求出n的拆分成一些数字的和。每个拆分后的序列中的数字从小到大排序。然后你需要输出这些序列,其中字典序小的序列需要优先输出。
输入格式
输入:待拆分的自然数n。
输出格式
输出:若干数的加法式子。
输入输出样例
输入 #1
7
输出 #1
1+1+1+1+1+1+1
1+1+1+1+1+2
1+1+1+1+3
1+1+1+2+2
1+1+1+4
1+1+2+3
1+1+5
1+2+2+2
1+2+4
1+3+3
1+6
2+2+3
2+5
3+4
import java.util.*;
public class Main {
public static void main(String[] args) {
new Main().sf();
}
int n = 0;
int[] a = new int[11];
public void sf() {
Scanner in = new Scanner(System.in);
n = in.nextInt();
in.close();
dfs(0, 1, 1);
}
public void dfs(int he,int c,int qs) {
if (he == n) {
for (int i = 1; i <= c-2; i++) {
System.out.print(a[i]+"+");
}
System.out.println(a[c-1]);
return;
}
if (he > n) {
return;
}
for (int i = qs; i <= n - 1; i++) {
a[c] = i;
dfs(he + i, c + 1, i);
a[c] = 0;
}
}
}
import java.util.*;
public class Main {
int n = 0, m = 0;
int[] a = new int[20];
public void dfs(int pos) {
for (int i = a[pos - 1]; i <= m; i++) {
if (i == n) {
continue;
}
a[pos] = i;
m-=i;
if (m == 0) {
prin(pos);
} else {
dfs(pos + 1);
}
m+=i;
}
}
public void prin(int aa) {
for (int i = 1; i < aa; i++) {
System.out.print(a[i]+"+");
}
System.out.println(a[aa]);
}
public static void main(String[] args) {
new Main().sf();
}
public void sf() {
Scanner in = new Scanner(System.in);
n = in.nextInt();
m = n;
for (int i = 0; i < a.length; i++) {
a[i] = 1;
}
dfs(1);
}
}