面试过程中关于台阶算法的代码解决方案
- 台阶问题
- 要爬十级台阶,一次可以爬一级, 也可以爬两级, 也可以爬三级,总共多少种爬法
- 个人见解, 若有问题,欢迎指正,共同进步, 谢谢
'''
# Created on 八月-22-19 22:02
# test1.py
# @author: zhugelaoliu
# @DESC: 使用代码解决面试中的台阶问题
'''
from itertools import combinations, combinations_with_replacement, permutations
class Step():
"""
主要解决面试过程中 关于台阶算法的问题
解决思路:
1. 先求出最少和最多的次数
2. 再对步数进行最少次数和最多次数的组合,并筛选出其中可以登上台阶的组合
3. 对每个组合进行元素数量不变的排序
4. 去重.
step_nums int 是共有多少个台阶
allowed_steps list 元素为int, 允许每次上的台阶数list
"""
def __init__(self, step_nums, allowed_steps):
self.step_nums = step_nums
self.allowed_steps = allowed_steps if allowed_steps and isinstance(allowed_steps, list) else [1]
self.max_steps = self.step_nums // min(self.allowed_steps ) if self.step_nums % min(self.allowed_steps ) == 0 else self.step_nums // min(self.allowed_steps ) + 1
self.min_steps = self.step_nums // max(self.allowed_steps ) if self.step_nums % max(self.allowed_steps ) == 0 else self.step_nums // max(self.allowed_steps ) + 1
self.list1 = range(self.min_steps, self.max_steps + 1)
def get_all_combinations(self):
"""
获取所有的可以登上台阶的组合
"""
all_combinations = []
for i in self.list1:
for e in combinations_with_replacement(self.allowed_steps, i):
if sum(e) == self.step_nums:
all_combinations.append(e)
return all_combinations
def get_all_permutations(self):
"""
将组合进行排序
"""
results = []
for f in self.get_all_combinations():
for g in permutations(f, len(f)):
results.append(g)
return results
@property
def get_result(self):
"""
去重, 并打印结果
"""
results = list(set(self.get_all_permutations()))
print(f'使用{self.allowed_steps}这些步数, 登上 {self.step_nums} 个台阶,共有 {len(results)} 种方法, 方法如下:')
print(results)
if __name__ == "__main__":
step = Step(step_nums=10, allowed_steps=[1, 2, 3])
step.get_result