Skip to content

Commit a8a6550

Browse files
Merge pull request #694 from 7saheelahmed/7dev
Added new coding problem
2 parents fcd347c + 93a7e3e commit a8a6550

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# There's a staircase with N steps, and you can climb 1 or 2 steps at a time. Given N, write a function that returns the number of unique
2+
# ways you can climb the staircase. The order of the steps matters.
3+
4+
# For example, if N is 4, then there are 5 unique ways:
5+
6+
# 1, 1, 1, 1
7+
# 2, 1, 1
8+
# 1, 2, 1
9+
# 1, 1, 2
10+
# 2, 2
11+
12+
# What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X?
13+
# For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time. Generalize your function to take in X.
14+
15+
# Solution using Dynamic Programming
16+
17+
# TC : O(N*|x|)
18+
# SC : O(N)
19+
20+
def num_ways_X(n):
21+
if n==0:
22+
return 1
23+
total = 0
24+
for i in x:
25+
if n-i>=0:
26+
total+=num_ways_X(n-i)
27+
28+
return total
29+
30+
def num_ways_dp(n):
31+
if n==0:
32+
return 1
33+
temp = [0]*(n+1)
34+
temp[0] = 1
35+
i = 1
36+
while i<n+1:
37+
total=0
38+
for j in x:
39+
if i-j>=0:
40+
total+=temp[i-j]
41+
temp[i]=total
42+
i+=1
43+
return temp[n]
44+
45+
x = [1,3,5]
46+
for i in range(1,40):
47+
print(num_ways_dp(i))
48+
49+

0 commit comments

Comments
 (0)