【问题标题】:Is it possible to change this recursion to a iteration without stack?是否可以将此递归更改为没有堆栈的迭代?
【发布时间】:2021-09-10 18:52:46
【问题描述】:

以下代码使用深度优先搜索算法递归生成排列,我想知道如何在没有堆栈的情况下更改为迭代等效(可以使用指针)。注意,这和遍历树很像,我尝试使用this link中提到的方法,但是总是不成功。

#include <stdio.h>

#define N 3
int A[N];

void dfs(int n, int mask) {
    if (n == N) {
        for (int j = 0; j < N; ++j) {
            printf("%d ", A[j]);
        }
        puts("");
    } else
        for (int i = 0; i < N; i++)
            if ((mask & (1 << i)) == 0) {
                A[n] = i + 1;
                dfs(n + 1, mask | (1 << i));
            }
}

int main() {
    dfs(0, 0);
}

【问题讨论】:

  • 您链接的问答已经表明这是可能的(假设它相当于遍历一棵树)。 “可能吗?”问题不太好,因为答案要么只是“是”或“否”。将其解释为“请给我密码?!”也不是一个好问题。当您遇到代码问题时,最好显示该代码,无论它多么损坏。目前尚不清楚为什么您应用该答案没有成功。
  • 您可能希望在 Find all possible combinations of numbers 问题中看到my answer。它与您的算法不同,它是用 C 语言而不是 C++ 编写的,但我希望它可能会有所帮助。
  • 更改问题以使现有的正确答案错误通常被视为bad behavior
  • @DrewDormann 我和你在一起,但也考虑到原来的问题已经说明“我想知道如何在没有堆栈的情况下更改为等效迭代(可以使用指针)”
  • @DrewDormann 现在我想想答案确实回答了这个问题;)

标签: c++ algorithm recursion iteration permutation


【解决方案1】:

您可以使用std::next_permutation 来生成排列。

#include <stdio.h>
#include <algorithm>

#define N 3
int A[N];

void perm() {
    for (int i = 0; i < N; i++) {
        A[i] = i + 1;
    }
    do {
        for (int j = 0; j < N; ++j) {
            printf("%d ", A[j]);
        }
        puts("");
    } while (std::next_permutation(A, A + N));
}

int main() {
    perm();
}

【讨论】:

  • 谢谢。其实我知道这种方式。我想知道的是如何用迭代来重写原来的算法。
  • #define N 3 很难看,应该用constconstexpr 代替。有guideline for that
  • @expression 链接有一个possible implementation
猜你喜欢
  • 2021-03-30
  • 2014-09-05
  • 2015-10-26
  • 2018-12-02
  • 2017-07-16
  • 2017-03-12
  • 2019-03-01
  • 2013-04-15
相关资源
最近更新 更多