#include<iostream> #include<algorithm> #include<iterator> #include<set> using namespace std; /* *整数划分问题并显示每一种分法 */ set<multiset<int>> GetAllIntDivision(int n) { set<multiset<int>> allDivision; if(1==n) { multiset<int> aa; aa.insert(1); allDivision.insert(aa); } else { set<multiset<int>> iniDivision = GetAllIntDivision(n-1); for(set<multiset<int>>::iterator iter = iniDivision.begin();iter != iniDivision.end();iter++) { //添加后缀项 multiset<int> inimul; inimul = *iter; inimul.insert(1); allDivision.insert(inimul); //添加累加项 /*inimul = *iter;*/ for (multiset<int>::iterator it = (*iter).begin();it!=(*iter).end();++it) { multiset<int>::iterator iit = it; inimul = *iter; while((++iit)!=(*iter).end()&&(*it)==(*iit)) { iit = (++it); } inimul.erase(inimul.find(*it)); inimul.insert((*it)+1); allDivision.insert(inimul); } } } return allDivision; } int main() { set<multiset<int>> allDivision; allDivision = GetAllIntDivision(6); //输出结果 for(set<multiset<int>>::iterator iter = allDivision.begin();iter != allDivision.end();iter++) { copy((*iter).begin(),(*iter).end(),ostream_iterator<int>(cout," ")); cout<<endl; } return 0; }
原文地址:http://blog.csdn.net/yyc1023/article/details/41010231