CS 61A 2021 Fall Disc 04 Q2: Count K

这篇博客讨论了一个特殊的台阶问题变体,其中每次可以跨越1到k步。作者提出了一个名为count_k的递归函数来解决此问题,并给出了分析和代码实现。代码包括了基础的count_stair_ways函数(只允许1或2步的情况)以及count_k函数,通过递归和循环来计算不同路径的数量。博客还分享了一位北大大佬的CS学习建议,强调了自我学习的重要性。
摘要由CSDN通过智能技术生成

CS 61A 2021 Fall Disc 04 Q2: Count K

  • 题目
    Consider a special version of the count_stair_ways problem, where instead of taking 1 or 2 steps, we are able to take up to and including k steps at a time. Write a function count_k that figures out the number of paths for this scenario. Assume n and k are positive.
  • 分析
    是经典台阶问题的进阶问题,需要考虑新的递归范式
    本人考虑的是如下递归规则:

跨越步数最大到了K + 跨越步数最大到k-1

其中 跨越步数最大到K 的部分考虑如下递归规则:

第一步跨越了第K步+第一步用其他步数但后面的最大步数到了K步
  • 代码
    因为用了Q1编写的函数,先附上Q1的代码。Q1就是Q2中只能用1步和2步走对应的特殊情况。
def count_stair_ways(n):
    """Returns the number of ways to climb up a flight of
    n stairs, moving either 1 step or 2 steps at a time.
    >>> count_stair_ways(4)
    5
    """
#     "*** YOUR CODE HERE ***"
    if n==1:
        return 1
    if n==2:
        return 2
    if n<=0:
        return 0
    else:
        return count_stair_ways(n-1)+count_stair_ways(n-2)

然后下面是本人写的Q2的代码,反正是过了题目给的四个简单测试,对不对也不清楚,大家可以一起探讨下

def count_k(n, k):
    """ Counts the number of paths up a flight of n stairs
    when taking up to and including k steps at a time.
    >>> count_k(3, 3) # 3, 2 + 1, 1 + 2, 1 + 1 + 1
    4
    >>> count_k(4, 4)
    8
    >>> count_k(10, 3)
    274
    >>> count_k(300, 1) # Only one step at a time
    1
    """
    "*** YOUR CODE HERE ***"
    def count_must_k(n,k):
        if n<k:
            return 0
        if n==k:
            return 1
        else:
            return_values = 0
            return_values += count_k(n - k, k)  # 1
            for i in range(k - 1):
                return_values += count_must_k(n - i - 1, k)
            # return_values+=count_k(k,k-1)*count_must_k(n-k,k)
            # return_values += count_k(n, k - 1)
            return return_values
            # return count_k(n,k)
        pass
    if n==0:
        return 0
    if n==1:
        return 1
    if k==1:
        return 1
    if k==2:
        return count_stair_ways(n)
    if k>n:
        return count_k(n,n)
    if k==n:
        return 1+count_k(n,k-1)# 4 3
    if k<=0:
        return 0
    else:
        return_values=0
        return_values+=count_k(n-k,k) #1
        for i in range(k-1):
            return_values+=count_must_k(n-i-1,k)
        # return_values+=count_k(k,k-1)*count_must_k(n-k,k)
        return_values+=count_k(n,k-1)
        return return_values

可能能看到这的都是在国内念大学的萌新,这里推荐一个北大大佬写的CS学习建议,如果让我用一句话总结,那就是:CS只能自学(狗头狗头狗头

> https://csdiy.wiki

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值