Skip to content

Commit e5a929d

Browse files
committed
Add basic recursion algorithms
1 parent 7f60d57 commit e5a929d

File tree

5 files changed

+68
-0
lines changed

5 files changed

+68
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package com.thealgorithms.recursion;
2+
3+
public class Factorial {
4+
5+
public static int factorial(int n) {
6+
if (n == 0) {
7+
return 1;
8+
}
9+
return n * factorial(n - 1);
10+
}
11+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package com.thealgorithms.recursion;
2+
3+
public class Fibonacci {
4+
5+
public static int fibonacci(int n) {
6+
if (n <= 1) {
7+
return n;
8+
}
9+
return fibonacci(n - 1) + fibonacci(n - 2);
10+
}
11+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.thealgorithms.recursion;
2+
3+
import java.util.ArrayList;
4+
5+
public class Permutations {
6+
7+
public static void permute(String str, String prefix, ArrayList<String> result) {
8+
if (str.length() == 0) {
9+
result.add(prefix);
10+
} else {
11+
for (int i = 0; i < str.length(); i++) {
12+
String rem = str.substring(0, i) + str.substring(i + 1);
13+
permute(rem, prefix + str.charAt(i), result);
14+
}
15+
}
16+
}
17+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.thealgorithms.recursion;
2+
3+
import java.util.ArrayList;
4+
5+
public class Subsets {
6+
7+
public static void subset(String prefix, String str, ArrayList<String> result) {
8+
if (str.length() == 0) {
9+
result.add(prefix);
10+
return;
11+
}
12+
subset(prefix + str.charAt(0), str.substring(1), result);
13+
subset(prefix, str.substring(1), result);
14+
}
15+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.thealgorithms.recursion;
2+
3+
public class TowerOfHanoi {
4+
5+
public static void solve(int n, char from, char to, char aux) {
6+
if (n == 1) {
7+
System.out.println("Move disk 1 from rod " + from + " to rod " + to);
8+
return;
9+
}
10+
solve(n - 1, from, aux, to);
11+
System.out.println("Move disk " + n + " from rod " + from + " to rod " + to);
12+
solve(n - 1, aux, to, from);
13+
}
14+
}

0 commit comments

Comments
 (0)