1. 3的倍數枚舉(基礎)
題目:在之間有10和50多少個數是3的倍數?列舉這些數。
解析:
枚舉10到50之間的數,判斷是否能被3整除。
優化:計算第一個≥10的3的倍數(12=3×4),最后一個≤50的3的倍數(48=3×16),總數=16-4+1=13個。
代碼:
cpp
#include <iostream> using namespace std; int main() {int count = 0;for (int i = 10; i <= 50; i++) {if (i % 3 == 0) {cout << i << " ";count++;}}cout << "\nTotal: " << count << " numbers";return 0; }
輸出:
text
12 15 18 21 24 27 30 33 36 39 42 45 48 Total: 13 numbers
2. 硬幣組合枚舉(分類枚舉)
題目:用1元、2元、5元硬幣湊出10元,共有多少種組合?(每種至少用1枚)
解析:
枚舉5元硬幣的可能數量(最多2枚),再枚舉2元硬幣的數量,計算1元硬幣的數量。
確保總金額=10元且每種硬幣≥1枚。
代碼:
cpp
#include <iostream> using namespace std; int main() {int count = 0;for (int five = 1; five <= 2; five++) {for (int two = 1; two <= (10 - five * 5) / 2; two++) {int one = 10 - five * 5 - two * 2;if (one >= 1) {cout << "5元×" << five << " + 2元×" << two << " + 1元×" << one << endl;count++;}}}cout << "Total: " << count << " ways";return 0; }
輸出:
text
5元×1 + 2元×1 + 1元×3 5元×1 + 2元×2 + 1元×1 Total: 2 ways
3. 數字排列枚舉(有序枚舉)
題目:用數字1、3、5組成無重復的兩位數,列舉所有可能。
解析:
枚舉十位數(1、3、5),再枚舉個位數(不能與十位重復)。
代碼:
cpp
#include <iostream> using namespace std; int main() {int digits[] = {1, 3, 5};for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {if (digits[i] != digits[j]) {cout << digits[i] * 10 + digits[j] << " ";}}}return 0; }
輸出:
text
13 15 31 35 51 53
4. 臺階走法枚舉(遞推枚舉)
題目:有5級臺階,每次可走1級或2級,共有多少種走法?列舉所有走法。
解析:
枚舉1級和2級的組合,確保總步數=5。
例如:1+1+1+1+1、1+1+1+2、1+2+2等。
代碼:
cpp
#include <iostream> using namespace std; int main() {int count = 0;for (int two = 0; two <= 2; two++) { // 最多2步2級int one = 5 - two * 2;if (one >= 0) {cout << "1級×" << one << " + 2級×" << two << endl;count++;}}cout << "Total: " << count << " ways";return 0; }
輸出:
text
1級×5 + 2級×0 1級×3 + 2級×1 1級×1 + 2級×2 Total: 3 ways
5. 長方形拼法枚舉(幾何枚舉)
題目:用12個相同的小正方形拼成長方形,共有多少種拼法?(長≥寬)
解析:
枚舉長和寬的組合,使得長×寬=12。
例如:12×1、6×2、4×3。
代碼:
cpp
#include <iostream> using namespace std; int main() {int count = 0;for (int width = 1; width <= 12; width++) {if (12 % width == 0) {int length = 12 / width;if (length >= width) {cout << length << "×" << width << endl;count++;}}}cout << "Total: " << count << " ways";return 0; }
輸出:
text
12×1 6×2 4×3 Total: 3 ways
總結
以上題目涵蓋:
基礎枚舉(3的倍數)
組合枚舉(硬幣問題)
排列枚舉(數字組合)
遞推枚舉(臺階走法)
幾何枚舉(長方形拼法)