Last active
March 17, 2022 12:07
-
-
Save marilira/817648fd9a6bbf41a35b39167f102882 to your computer and use it in GitHub Desktop.
Backtracking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Gerar todos os subconjuntos do conjunto {..., n - 1} | |
#include <iostream> | |
using namespace std; | |
const int MAXN = 20; // maior quantidade de elementos para leitura | |
int n; | |
void backtracking(int i, bool choosed[]) | |
{ | |
if (i == n) // todos os números já foram selecionados | |
{ | |
for (int j = 0; j < n; j++) | |
if (choosed[j]) | |
cout << j << ' '; | |
cout << '\n'; | |
return; | |
} | |
choosed[i] = false; | |
backtracking(i + 1, choosed); // não escolher i na resposta atual | |
choosed[i] = true; | |
backtracking(i + 1, choosed); // escolher o na resposta atual | |
} | |
int main() | |
{ | |
bool choosed[MAXN]; | |
cin >> n; | |
cout << "All subsets: " << '\n'; | |
backtracking(0, choosed); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python tem um limite para a profundidade da recursão inferior ao do C++ | |
import sys | |
sys.setrecursionlimit(10**8) | |
MAXN = 20 | |
def backtracking(i, choosed): | |
if i == n: | |
for j in range(n): | |
if choosed[j]: | |
print(j, end=' ') | |
print() | |
return | |
choosed[i] = False | |
backtracking(i + 1, choosed) | |
choosed[i] = True | |
backtracking(i + 1, choosed) | |
choosed = [0]*MAXN | |
n = int(input()) | |
print("All subsets: ") | |
backtracking(0, choosed) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Indo ainda mais a fundo com a recursão | |
# Você tem controle sobre a pilha de recursões dentro da Thread | |
import sys, threading | |
sys.setrecursionlimit(10**9) | |
threading.stack_size(10**8) | |
def main(): | |
# Todo o seu código vai aqui | |
# Lança a função principal dentro da Thread | |
threading.Thread(target=main).start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment