一个整数可以有多种划分,使其分划的一列正整数之和为 。例如:
输入:n=6
输出文件,格式内容为
6=1+5
6=1+1+4
6=1+1+1+3
6=1+1+1+1+2
6=1+1+1+1+1+1
6=1+1+2+2
6=1+2+3
6=2+4
6=2+2+2
6=3+3
total=10
一个正整数
可拆分成的所有不重复等式,一行一个等式,有一定顺序;
最后再输出一行,total=个数
6
6=1+5
6=1+1+4
6=1+1+1+3
6=1+1+1+1+2
6=1+1+1+1+1+1
6=1+1+2+2
6=1+2+3
6=2+4
6=2+2+2
6=3+3
total=10
把一个正整数拆分成加法算式,第一位字典序小且后面字典序大的先输出
#include <bits/stdc++.h>
using namespace std;
int j;
void partition(int n, int last, vector<int>& current, vector<vector<int>>& result) {
if (n == 0) {
result.push_back(current);
return;
}
for (int i = (last == 0 ? 1 : last); i <= n; ++i) {
current.push_back(i);
partition(n - i, i, current, result);
current.pop_back();
}
}
void printPartitions(const vector<vector<int>>& partitions, int n) {
for (const auto& partition : partitions) {
if(partition[0]==n)continue;
cout << n << "=";
for (size_t i = 0; i < partition.size(); ++i) {
cout << partition[i];
if (i < partition.size() - 1) {
cout << "+";
}
}
cout << endl;
}
cout << "total=" << partitions.size()-1 << endl;
}
bool comparePartitions(const vector<int>& a, const vector<int>& b) {
if (a.size() != b.size()) {
return a.size() < b.size();
}
for (size_t i = 0; i < a.size(); ++i) {
if (a[i] != b[i]) {
return a[i] < b[i];
}
}
return false;
}
int main() {
cin >> j;
vector<vector<int>> partitions;
vector<int> current;
partition(j, 0, current, partitions);
sort(partitions.begin(), partitions.end(), comparePartitions);
printPartitions(partitions, j);
return 0;
}