面試過程中關於臺階算法的代碼解決方案
- 臺階問題
- 要爬十級臺階,一次可以爬一級, 也可以爬兩級, 也可以爬三級,總共多少種爬法
- 個人見解, 若有問題,歡迎指正,共同進步, 謝謝
'''
# 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