问题描述:
输入一个大于等于1的整数,输出满足下面格式的基础向量:
向量的最大元素值不大于n;
各向量元素按照递增顺序排列,即靠后的任意元素均大于它的前面的元素。
基础向量是可以通过各元素均加上某一数构成满足上述方式的基元向量
问题解答:
采用在基本向量后附加一个元素,求解向量个数多一的新的基元向量。
#include <iostream>
#include <vector>
using namespace std;
//得到p维向量的个数。该向量的元素成递增趋势,且各个向量元素值最大不超过n.
//将i维的向量的总个数存储到向量numberVector的第i-1位中
//lastElementsOfVector:存储某i维(i < p)向量最后一位元素
unsigned long long getP_DimensionVectorNumber(const int n,const int p,vector<unsigned long long> &numberVector)
{
if((1 > n)||(n < p)||(p < 1))
return 0;
numberVector.at(0) = 1; //1维向量有1个,即:{1}
unsigned long long rows = n - 1;
if(0 < rows){ //p维向量个数,在分配存储种子向量的矩阵时作为行数
//2维向量有n-1个,即:{1,2},{1,3},{1,4},...,{1,p}
numberVector.at(1) = rows;
}
else//n == 1 无须继续
return numberVector.at(0);
vector<int> lastElementsOfVector;
int i;
//初始时,存取的是二维向量的最后一位:2,3,...,n
for(i = 1;i < n;i++)
lastElementsOfVector.push_back(i+1);
vector<int> newVector(lastElementsOfVector); //暂存lastElementsOfVector的元素值
int indexSum = 2; //已经存取了2个,因此计数从2开始
int rowNumber = 0;
for(rowNumber = 0;rowNumber < n-2;rowNumber++)
{
lastElementsOfVector.clear();
lastElementsOfVector.reserve(n);
rows = 0;
unsigned long long j = 0;
for(j = 0;j < newVector.size();j++)
{
int currentValue = newVector.at(j);
if(currentValue < n)
{
int k = 1;
//算出新的种子向量最后一位可能取得值的总数,比如
//初始种子向量为(1,2)2维向量,要生成长度为3的3维向量向量;向量最大元素值为5,则3维种子向量最后一位可以是3,4,5共3种
int maxValue = n - currentValue;
rows += maxValue;
for(k = 1;k <= maxValue;k++){
lastElementsOfVector.push_back(currentValue+k);
}
}
}
//统计完该维度向量的总个数,将它压入numberVector中
numberVector.at(indexSum++) = rows;
//将numberVector赋值给newVector
newVector.clear();
newVector.reserve(lastElementsOfVector.size());
for(j = 0;j < lastElementsOfVector.size();j++)
{
newVector.push_back(lastElementsOfVector.at(j));
}
}
return numberVector.at(p-1);
}
//输出向量元素
void printVector(const vector<unsigned long long> &intVector)
{
int i = 0;
int len = intVector.size();
for(;i < len;i++)
{
cout<<intVector[i]<<"\t";
if(0 == ((i+1)%5)) //每5个元素输出后换行
cout<<endl;
}
}
int main()
{
cout << "please input the maximum value of the element:" << endl;
int n = 5;
cin>>n;
if(1 > n)
{
cerr<<"n must be larger than 0.!"<<endl;
return -1;
}
int p = 3;
cout<<"please input the vector dimension:(must be smaller than n you input just now.):\n";
cin>>p;
int resultOfCompute = 3;
vector <unsigned long long> numberVector(n);
resultOfCompute = getP_DimensionVectorNumber(n,p,numberVector);
if(-1 == resultOfCompute)
cerr<<"your input is illegal. please check if:(1 > n) or (n < p) or (p < 1)"<<endl;
else
{
cout<<"total number of p dimension vector whose maximum value is :"<<resultOfCompute<<endl;
cout<<"number of vectors whose dimension is between 1 and n is as follows(the first one stands for the number of 1 dimension vector,and the last one stands for the n dimension vector.):"<<endl;
printVector(numberVector);
}
return 0;
}