Saturday, January 29, 2022

Get stair paths

I/P: 3
O/P: [111, 12, 21, 3]





import java.util.ArrayList;

public class GetStairPath {
public static void main(String[] args) {
int n = 3;
ArrayList<String> ans = getStairPath(n);
System.out.println(ans);
}

private static ArrayList<String> getStairPath(int n) {
// base case
if (n == 0) {
ArrayList<String> bres = new ArrayList<>();
bres.add("");
return bres; // iska size 1 hoga toh step append ho jaega isme
} else if (n < 0) {
ArrayList<String> bres = new ArrayList<>();
return bres; // iska size empty hoga toh kuch bhi add ni hoga ans me
}

// faith
ArrayList<String> n1 = getStairPath(n - 1);
ArrayList<String> n2 = getStairPath(n - 2);
ArrayList<String> n3 = getStairPath(n - 3);

// expectation meet faith
ArrayList<String> ans = new ArrayList<>();

for (String step : n1) {
ans.add(step + "1");
}
for (String step : n2) {
ans.add(step + "2");
}
for (String step : n3) {
ans.add(step + "3");
}
return ans;
}
}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...