© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
6 replies
morry329#

✅ What is the function of the Dictionary here?

public class Solution {
Dictionary<int,int>cached=new Dictionary<int,int>();

public int ClimbStairs(int n) {
if(cached.ContainsKey(n)) {
return cached[n];
}
int output = 1;
if(n<=3){
output = n;
} else {
output = ClimbStairs(n-1) + ClimbStairs(n-2);

}
cached[n]=output;
return output;
}
}

So I wanted to understand the above solution for this LeetCode puzzle https://leetcode.com/problems/climbing-stairs/description/

I am still wondering what the Dictionary is doing here. My guess is that it prevents the code from exceeding the time limit (as my code went to exceed the limit without the Dictionary). But I appreciate any other plausible explanation for the Dictionary's presence here.
LeetCode
Climbing Stairs - LeetCode
Can you solve this real interview question? Climbing Stairs - You are climbing a staircase. It takes n steps to reach the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

 

Example 1:


Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps...
Climbing Stairs - LeetCode
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ What is reason of null! here?
C#CC# / help
2y ago
✅ wtf? what is the problem here?
C#CC# / help
2y ago
❔ What is the use of datatype after function name?
C#CC# / help
4y ago
What is the cause of the error here in my repository?
C#CC# / help
16mo ago