Let’s write a recursive solution to the factorial problem
ArrayList
What if we wanted to store all intermediate results in an array?
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
ArrayList
solutionimport java.util.ArrayList;
public class RecursiveFactorial {
public static int factorial(int n, ArrayList<Integer> allResults) {
if (n == 0) {
allResults.add(1);
return 1;
}
else {
int subResult = n * factorial(n - 1, allResults);
allResults.add(subResult);
return subResult;
}
}
public static void main(String[] args) {
ArrayList<Integer> result = new ArrayList<Integer>();
factorial(10, result);
System.out.println(result);
}
}
You have 10 minutes to complete the quiz.
No need to write comments.
Name your method what you want, but the name should be in camelCase.
These are brute-force
algorithms
Used for problems that have a small and well-defined search space, where it is feasible to check all possible solutions
Also called recursive enumeration
Main idea: systematically identify every possible solution to a problem
Write a Java application that given an integer n
, it prints all binary numbers that have n
digits.
Make sure your application outputs one binary number per line, in ascending order.
HINTS:
'0'
or '1'
The call:
getBinary(3, "");
Prints out:
000
001
010
011
100
101
110
111
public class AllBinary {
public static void getBinary(int digits, String number) {
if (digits == 0) { // base case, no digits left to add
System.out.println(number);
} else {
getBinary(digits - 1, number + "0");
getBinary(digits - 1, number + "1");
}
}
public static void main(String[] args) {
getBinary(3, "");
}
}
ArrayList
of solutionsWhat if instead of printing out a solution, I wanted to create an ArrayList
of solutions?
Write a Java application that given an integer n
, it prints all decimal numbers that have n
digits.
HINT:
The call:
getDecimal(2, "");
Prints out:
00
01
02
03
..
94
95
96
97
98
99
import java.util.ArrayList;
public class AllDecimal {
public static void getDecimal(int digits, String number, ArrayList<String> result) {
if (digits == 0) {
result.add(number);
} else {
for (int n = 0; n < 10; n++) {
getDecimal(digits - 1, number + n, result);
}
}
} // getDecimal
public static void main(String[] args) {
ArrayList<String> result = new ArrayList<String>();
getDecimal(2, "", result);
for (String number : result) {
System.out.println(number);
}
}
}