自然数n的分解
2015-07-13 16:41
429 查看
输入自然数n(n<100),输出所有和的形式。不能重复。
如:4=1+1+2;4=1+2+1;4=2+1+1 属于一种分解形式。
样例:
输入:
7
输出:
7=1+6
7=1+1+5
7=1+1+1+4
7=1+1+1+1+3
7=1+1+1+1+1+2
7=1+1+1+1+1+1+1
7=1+1+1+2+2
7=1+1+2+3
7=1+2+4
7=1+2+2+2
7=1+3+3
7=2+5
7=2+2+3
7=3+4
分析:
假设n=a[1]+a[2]+...+a
,为了避免分解重复,可以约定a[1]≤a[2]≤...≤a
,
假设当前已经分解出cur项,待分解的数字为m(m=n-a[1]-a[2]...-a[cur]);
则 a[1],a[2],...,a[cur],m即是一种分解方案(cur>0)
如何继续分解呢,a[cur+1]=?
a[cur+1]的取值范围:a[cur]~m/2 (因为 m-a[cur+1]>=a[cur+1],则a[cur+1]/2<=m才能继续分解)
代码:
View Code
如:4=1+1+2;4=1+2+1;4=2+1+1 属于一种分解形式。
样例:
输入:
7
输出:
7=1+6
7=1+1+5
7=1+1+1+4
7=1+1+1+1+3
7=1+1+1+1+1+2
7=1+1+1+1+1+1+1
7=1+1+1+2+2
7=1+1+2+3
7=1+2+4
7=1+2+2+2
7=1+3+3
7=2+5
7=2+2+3
7=3+4
分析:
假设n=a[1]+a[2]+...+a
,为了避免分解重复,可以约定a[1]≤a[2]≤...≤a
,
假设当前已经分解出cur项,待分解的数字为m(m=n-a[1]-a[2]...-a[cur]);
则 a[1],a[2],...,a[cur],m即是一种分解方案(cur>0)
如何继续分解呢,a[cur+1]=?
a[cur+1]的取值范围:a[cur]~m/2 (因为 m-a[cur+1]>=a[cur+1],则a[cur+1]/2<=m才能继续分解)
代码:
#include<iostream> #include<cstring> using namespace std; int a[100],b[100]; int s=0, n; void dfs(int cur,int m){ if (cur>0){ s++; cout<<n<<"="; for (int i=1;i<=cur;i++) cout<<a[i]<<"+"; cout<<m<<endl; } for (int i=a[cur];i<=m/2;i++){ a[cur+1]=i; dfs(cur+1,m-i); } } int main(){ memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); cin>>n; a[0]=1; dfs(0,n); cout<<s<<endl; return 0; }
View Code
相关文章推荐
- 黑马程序猿——JAVA基础------内部类
- java排列组合算法
- 生成模型与判别模型
- poj 3046 数蚂蚁 dp
- 常用iOS第三方库以及XCode插件介绍
- html5之DeviceOrientation 手机重力与方向感应
- python_1(基础知识)
- javascript中对变量类型的判断
- 【Support Vector Regression】林轩田机器学习技法
- iframe 如何让它展现内容自适应高度
- Unity3D它Button包
- android raw与assets区别
- iOS设计模式——Category
- [leetcode] 146.LRU Cache
- 欢迎使用CSDN-markdown编辑器
- Android开发之如何监听让服务不被杀死(service+broadcast)
- 多层级的makefile编写——递归调用makefile
- NDK积累
- EXTJS store 某行某列数据更新等操作
- [LeetCode] Happy Number