汉诺塔变种(递归)
每次只允许将圆盘移到中间杆上或从中间杆上移出,不允许直接将圆盘从第一根杆上移到第二根杆上,或直接将圆盘从第三根杆上移到第一根杆上。
1 2 3 4 5 6
| long long solve(int n) if (n == 1) return 2; else return 3 * solve(n - 1) + 2; }
|
杨辉三角(递归)
1 2 3 4 5 6
| int solve(int r, int c) { if (r == 1 || c == 1 || r == c) return 1; return solve(r - 1, c - 1) + solve(r - 1, c); }
|
全排列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| const int MAXN = 10; char s[MAXN]; int vis[MAXN]; char res[MAXN];
void solve(char *s, int cnt) { if (cnt == strlen(s)) { for (int i = 0; i < strlen(res); ++i) cout << res[i] << ' '; cout << "\n"; } for (int i = 0; i < strlen(s); ++i) { if (!vis[i]) { vis[i] = 1; res[cnt] = s[i]; solve(s, cnt + 1); vis[i] = 0; } } }
|
计算二叉树子树节点个数
1 2 3 4 5 6 7 8 9
| int solve(int n, int m) { if (m > n) return 0; int res = 1; res += solve(n, 2 * m); res += solve(n, 2 * m + 1); return res; }
|
分解2的幂次方
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| string solve(int n) { stack<int> p; int exp = 0; while (n) { if (n % 2) p.push(exp); exp++; n /= 2; } string res = ""; while (!p.empty()) { if (p.top() == 0) res += "2(0)"; else if (p.top() == 1) res += "2"; else res += "2(" + solve(p.top()) + ")"; p.pop(); if (!p.empty()) res += "+"; } return res; }
|