一、输出效果
PS D:\cpp_works\OJ\build> ."D:/cpp_works/OJ/build/main.exe" 5 5=1+1+1+1+1 5=1+1+1+2 5=1+1+3 5=1+2+2 5=1+4 5=2+3 5=5
即输出5的所有求和的组合方式,不允许重复组合,如5=2+3和5=3+2是重复的。输出结果字符串需按字典序排序。
二、代码实现
#include <bits/stdc++.h>
using namespace std;
static bool cmp(const string& str1, const string& str2)
{
int i = 0;
while (i < str1.size() && i < str2.size()) {
if (str1[i] > str2[i]) {
return false;
} else if (str1[i] < str2[i]) {
return true;
}
i++;
}
if (str1.size() == str2.size()) {
return false;
} else if (str1.size() > str2.size()) {
return false;
} else {
return true;
}
}
class Solution32 {
public:
int n;
vector<string> ret;
void solve()
{
int n;
while (cin >> n) {
ret.clear();
vector<int> vec;
this->n = n;
dfs(n, n, vec);
sort(ret.begin(), ret.end(), cmp);
for (const auto& it : ret) {
cout << it << endl;
}
}
}
void dfs(int i, int j, vector<int>& vec)
{
if (j == 0) {
return;
} else if (i == 1 && j >= 1) {
vec.push_back(1);
show(vec, n);
vec.pop_back();
return;
}
if (i < j) {
dfs(i, i, vec);
} else if (i == j) {
dfs(i, j - 1, vec);
vec.push_back(j);
show(vec, n);
vec.pop_back();
} else if (i > j) {
// dp[i][j-1]
dfs(i, j - 1, vec);
// dp[i-j][j]
vec.push_back(j);
dfs(i - j, j, vec);
vec.pop_back();
}
}
void show(const vector<int>& vec, int n)
{
stringstream ss("");
streambuf* old = cout.rdbuf();
cout.rdbuf(ss.rdbuf());
cout << n << "=";
for (auto it = vec.rbegin(); it < vec.rend() - 1; it++) {
cout << *it << "+";
}
cout << *(vec.rend() - 1);
cout.rdbuf(old);
ret.push_back(ss.str());
}
};