提交时间:2026-06-19 16:23:36

运行 ID: 91925

#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int n; vector<string> ans; // 构造表达式并计算结果是否为 0 void dfs(int pos, int sum, int last, string s) { if (pos > n) { if (sum == 0) { ans.push_back(s); } return; } // 1. 插入空格:拼接数字 int num = last * 10 + pos; int new_sum = sum - last + num; dfs(pos + 1, new_sum, num, s + " " + to_string(pos)); // 2. 插入加号 dfs(pos + 1, sum + pos, pos, s + "+" + to_string(pos)); // 3. 插入减号 dfs(pos + 1, sum - pos, -pos, s + "-" + to_string(pos)); } int main() { cin >> n; dfs(2, 1, 1, "1"); // 按 ASCII 顺序输出(搜索顺序已经满足,直接输出即可) for (string &str : ans) { cout << str << endl; } return 0; }