cuốn sách gpt4 ai đã làm

c++ - 设计生成所有 n 位数字组合的递归函数的最佳方法是什么?

In lại Tác giả: Taklimakan 更新时间:2023-11-03 05:43:29 26 4
mua khóa gpt4 Nike

作为我在同事的算法类(class)的一部分,我们必须设计一个递归函数来生成 n 位数字的所有组合。

Đây là một ví dụ:

Ví dụ đầu vào:

3

示例输出:

111

112

113

121

122

123

131

132

133

211

212

213

221

222

223

231

232

233

311

312

313

321

322

323

331

332

333

我想指出,我已经解决了这个问题,这样人们就不会评论说这是作业,我必须自己做。无论如何,这是我的 C++ 代码:

void S6_1(int r, int n, int p, int d)
{
if (d == 0)
return;
S6_1(r, n, p, d - 1);
r = r * 10 + d;
if (p == 1)
cout << r << endl;
khác
S6_1(r, n, p - 1, n);
}

void S6(int n)
{
S6_1(0, n, n, n);
}

我发布这篇文章的主要原因是我坚信必须有另一种方法来解决这个问题。

非常感谢您提供的任何帮助

câu trả lời hay nhất

归纳思考:如何将生成所有包含 [1..n] 中数字的 n 位数字的问题分解为一个更小的自身实例并增加一点工作量?也许最明显的是将所有可能的数字添加到递归生成的所有 (n-1) 位数字的前面。我将使用 C(但 C++ 类似)在缓冲区中一次一个地累积数字。

// In buf[i..n-1], enumerate all numbers having n-i digits with values in [1..n]. 
void print_all(char *buf, int i, int n) {
if (i == n) { // Here n - i == 0, so we're done. Print.
printf("%.*s\n", n, buf);
return;
}
for (int digit = 1; digit <= n; ++digit) {
buf[i] = digit + '0'; // put a digit at position i
print_all(buf, i + 1, n); // recursively put the rest
}
}

调用它:

char buf[n];
print_all(buf, 0, n);

也可以像您一样在 int 中构建数字。代码有点短,但是它把将 int 分解成字符串的工作留给了 printf,所以从某种意义上说这是双重工作:

void print_all(int b, int i, int n) {
if (i == n) {
printf("%d\n", b);
return;
}
for (int digit = 1; digit <= n; ++digit) {
print_all(10 * b + digit, i + 1, n);
}
}

并称它为...

print_all(0, 0, n);

biên tập

正如我在评论中指出的那样,用更难理解的递归替换明显的循环应用程序并不明智。但是既然你问了,

// Enumerate all numbers formed by appending to the number in b all (n-i)-digit
// numbers starting with a digit in [d..n] and all other digits in [1..n].
void print_all(int d, int b, int i, int n) {
if (d > n) return;
if (i == n) {
printf("%d\n", b);
return;
}
print_all(1, 10 * b + d, i + 1, n); // enumerate all with more digits
print_all(d + 1, b, i, n); // enumerate other values of i'th digit
}

并调用:

print_all(1, 0, 0, n);

关于c++ - 设计生成所有 n 位数字组合的递归函数的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37533609/

26 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress