Skip to content

Commit

Permalink
Introduction to Backtracking, recursion and sets
Browse files Browse the repository at this point in the history
  • Loading branch information
Nanashii76 authored Feb 27, 2024
1 parent 4a4127e commit 88e0d9b
Show file tree
Hide file tree
Showing 5 changed files with 144 additions and 0 deletions.
38 changes: 38 additions & 0 deletions theory/backtracking/findingSubsets.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#include <iostream>

void findSubsets(char *input, char *output, int i, int j) {

//base case
if(input[i] == '\0') {
output[j] = '\0';
if(output[0]=='\0')
std::cout << "NULL";
std::cout << output << std::endl;
return;
}

//rec case
//include the ith letter
output[j] = input[i];
findSubsets(input, output, i+1, j+1);

//exclude the ith letter
output[j] = '\0';
findSubsets(input,output,i+1,j);

}




int main(){

char s[100], output[100];

std::cin >> s;
findSubsets(s,output,0,0);

}



44 changes: 44 additions & 0 deletions theory/backtracking/permutations.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#include <iostream>
#include <cstring>
#include <string>

void swap(char *a, char *b) {
char tmp = *a;
*a=*b;
*b=tmp;
}

/*
Given a string s, find all permutations of the string
*/

void permutationsString(char *n1, int l, int r) {

int i;
if(l == r)
std::cout << n1 << std::endl;

for(i = l; i <= r; ++i) {
swap((n1+l), (n1+i));
permutationsString(n1, l+1, r);
swap((n1+l),(n1+i));
}

}

int main(){

char str[100];
std::cin >> str;
int n = strlen(str);

permutationsString(str, 0 , n-1);


}



26 changes: 26 additions & 0 deletions theory/inclusion_and_exclusion/inclusion_exclusion.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Principles of Inclusion and Exclusion

-> Set Theory

Set is a form to store elements that doesn't repeat
Generally sets're sorted

'''
{AuB} = A + B - {A^B} -> union of the sets

-> Generalised function

'''
Discovering the pattern of even and odd sets
Let's see if we've 3 sets

|AuBuC| -> A + B + C
- |AB| - |AC| - |BC|
+ |ABC|

Now let's see for 4 sets

|AuBuCuD| -> A + B + C + D
- |AB| - |AC| - |BC|
+ |ABC| + |ABD| + |BCD| + |ACD|
- |ABCD|
19 changes: 19 additions & 0 deletions theory/recursion/factorial.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#include <iostream>


int factorial(int n) {

if (n == 1)
return 1;

return n*factorial(n-1);

}


int main(){

std::cout << factorial(5) << std::endl;


}
17 changes: 17 additions & 0 deletions theory/recursion/fibonnaci.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#include <iostream>

int fib(int n) {

if(n == 0 or n == 1)
return n;

return fib(n-1) + fib(n-2);

}


int main(){

std::cout << fib(5) << std::endl;

}

0 comments on commit 88e0d9b

Please sign in to comment.