题目
分析
本题用C++内置的排列组合函数next_permutation会非常直截了当:
// 枚举所有可能的排列
int nums[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
do
{
// 构造三个三位数
int num1 = nums[0] * 100 + nums[1] * 10 + nums[2];
int num2 = nums[3] * 100 + nums[4] * 10 + nums[5];
int num3 = nums[6] * 100 + nums[7] * 10 + nums[8];
// 检查比例是否符合要求
if (num1 * B == num2 * A && num1 * C == num3 * A)
{
cout << num1 << " " << num2 << " " << num3 << endl;
found = true;
}
} while (next_permutation(nums, nums + 9));
答案

思考
next_permutation 是 C++ 标准库中的函数,用于生成下一个字典序排列。
- 用法:
bool next_permutation(Iterator first, Iterator last)。在本例中,是9个数字的排列。 - 在本题应用:枚举1-9的所有排列,构造三位数检查比例。
- 注意:需包含
<algorithm>,序列可修改,先排序从最小开始。数组不能用nums.begin(), nums.end(),但可以用std::begin(nums), std::end(nums)(需<iterator>),或改用vector<int> nums = {1,2,3,4,5,6,7,8,9};(如最终解法),然后用nums.begin(), nums.end()。
