要求:
一个正整数n可以写为几个正整数的和,如:
4=4
4=3+1
4=2+2
4=2+1+1
4=1+1+1+1
输入一个正整数,找出符合这种要求的所有正整数序列(序列不重复)
算法思想:
以n=6为例,将数继序列暂时存于a[MAXCOL]中,且初始时值全为1。
对数组中从jcol列开始的newn个元素进行操作f(6,0,0) ——函数GetCombinations(newn,newj,col)
col记录调用该函数时是在第col列。
初始化
count=6
j=0,newn=0
count=n
1. 如果count>1,令a[jcol]=count;
若count>a[col],表明该尝试不满足条件,count=count-1,重复1;
否则将该行第jcol+1列到jcol+count-1列的值改为0;
否则,退出;
2. newn=n-count
3. 如果new>1,则对从该行开始从jcol+count开始的newn个元素进行类似操作,并返回该新的newn对应的序列个数;
否则,count=count-1,返回1。
算法比较:
“acm题目及我的程序(3)——正整数n的加法组合”——使用二维数组存放加法序列
#define MAXROW 12000
#define MAXCOL 20
#define MAXCOL 20
a[MAXROW][MAXCOL]
算法效率低,空间浪费严重
“acm题目及我的程序(3)——正整数n的加法组合(改进)”——使用二维数组存放加法序列
a[MAXROW][MAXCOL]
#define MAXROW 6000
#define MAXCOL 30
#define MAXCOL 30
算法效率高,空间浪费不严重
“acm题目及我的程序(3)——正整数n的加法组合(改进2)”——使用动态二维数组存放加法序列
vector<vector<int> > m_venline
算法效率高,空间浪费很少
本文算法——使用一维数组存放加法序列,且计算每个n的加法序列的个数
a[MAXCOL]
算法效率最高,空间根本不浪费
代码如下:
/**/
/************************************************************************
* 一个正整数n可以写为几个正整数的和
* 4=4
* 4=3+1
* 4=2+2
* 4=2+1+1
* 4=1+1+1+1
* 要求:输入一个正整数,找出符合这种要求的所有正整数序列(序列不重复)
************************************************************************/
#include < stdio.h >
#include < string .h >
#include < CONIO.H >
#include < vector >
using namespace std;
#define MAXCOL 80
#define FILENAMELENGTH 100
class AdditionCombination
... {
public:
int a[MAXCOL];
int m_number; //条用GetCombinations函数时count的值
public:
AdditionCombination(int number)
...{
m_number=number;
for(int j=0;j<MAXCOL;j++)
a[j]=1;
}
~AdditionCombination()...{}
void Initialize()
...
* 一个正整数n可以写为几个正整数的和
* 4=4
* 4=3+1
* 4=2+2
* 4=2+1+1
* 4=1+1+1+1
* 要求:输入一个正整数,找出符合这种要求的所有正整数序列(序列不重复)
************************************************************************/
#include < stdio.h >
#include < string .h >
#include < CONIO.H >
#include < vector >
using namespace std;
#define MAXCOL 80
#define FILENAMELENGTH 100
class AdditionCombination
... {
public:
int a[MAXCOL];
int m_number; //条用GetCombinations函数时count的值
public:
AdditionCombination(int number)
...{
m_number=number;
for(int j=0;j<MAXCOL;j++)
a[j]=1;
}
~AdditionCombination()...{}
void Initialize()
...