将一个整数分解,输出所有的加法可能(每个数字只能使用一次)解决方案
将一个整数分解,输出所有的加法可能(每个数字只能使用一次)
例如:
input: 10
output:
10=1+9
10=2+8
10=3+7
10=4+6
10=1+2+7
10=1+3+6
10=1+4+5
10=2+3+5
10=1+2+3+4
------解决方案--------------------
例如:
input: 10
output:
10=1+9
10=2+8
10=3+7
10=4+6
10=1+2+7
10=1+3+6
10=1+4+5
10=2+3+5
10=1+2+3+4
------解决方案--------------------
- C/C++ code
#include<stdio.h> int r[100]; int *q=r; int m; void output(int *p) { int *p1; printf("%d=%d",m,*q); for (p1=q+1;p1<=p;p1++) printf("+%d",*p1); printf("\n"); } void finder(int *p,int n,int x) { if (x-n>n) { for (;x-n>n;n++) { *p=n; if (x-n>=2*n+3) finder(p+1,n+1,x-n); *(p+1)=x-n; output(p+1); } } else return; } main() { printf("Input:"); scanf("%d",&m); finder(r,1,m); }
------解决方案--------------------
- C/C++ code
#include<stdio.h> #include<stdlib.h> void func(const int N, int sum, int cur, int res[], int depth) { if (sum <= 0) { if (0 == sum) { int i; for (i = 0; i < depth; ++i) { printf("%d ", res[i]); } printf("\n"); } } else { if (cur < N) { res[depth] = cur; func(N, sum - cur, cur + 1, res, depth + 1); func(N, sum, cur + 1, res, depth); } } } int main() { int res[10]; func(10, 10, 1, res, 0); system("pause"); return 0; }
------解决方案--------------------