RECURSION (Basics) SOLUTIONS
Solution 1:
public class Solution {
public static void allOccurences(int arr[], int key, int i) {
if(i == [Link]) {
return;
}
if(arr[i] == key) {
[Link](i+" ");
}
allOccurences(arr, key, i+1);
}
public static void main(String[] args) {
int arr[] = {3, 2, 4, 5, 6, 2, 7, 2, 2};
int key = 2;
allOccurences(arr, key, 0);
[Link]();
}
}
Solution 2:
public class Solution {
static String digits[] = {"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine"};
public static void printDigits(int number) {
if(number == 0) {
return;
}
int lastDigit = number%10;
printDigits(number/10);
[Link](digits[lastDigit]+" ");
}
public static void main(String[] args) {
printDigits(1234);
[Link]();
}
}
Solution 3 :
public class Solution {
public static int length(String str) {
if([Link]() == 0) {
return 0;
}
return length([Link](1)) + 1;
}
public static void main(String[] args) {
String str = "abcde";
[Link](length(str));
}
}
Solution 4 :
public class Solution {
public static int countSubstrs(String str, int i, int j, int n) {
if (n == 1) {
return 1;
}
if (n <= 0) {
return 0;
}
int res = countSubstrs(str, i + 1, j, n - 1) +
countSubstrs(str, i, j - 1, n - 1) -
countSubstrs(str, i + 1, j - 1, n - 2);
if ([Link](i) == [Link](j)) {
res++;
}
return res;
}
public static void main(String[] args) {
String str = "abcab";
int n = [Link]();
[Link](countSubstrs(str, 0, n-1, n));
}
}
Solution 5 :
public class Solution {
public static void towerOfHanoi(int n, String src, String helper, String dest) {
if(n == 1) {
[Link]("transfer disk " + n + " from " + src + " to " + dest);
return;
//transfer top n-1 from src to helper using dest as 'helper'
towerOfHanoi(n-1, src, dest, helper);
//transfer nth from src to dest
[Link]("transfer disk " + n + " from " + src + " to " + helper);
//transfer n-1 from helper to dest using src as 'helper'
towerOfHanoi(n-1, helper, src, dest);
}
public static void main(String args[]) {
int n = 4;
towerOfHanoi(n, "A", "B", "C");
}
}
The Solution for this particular question has also been discussed here :
[Link]
At timestamp : 00:05