程序员面试金典——递归问题汇总

本文汇总了程序员面试中常见的递归问题,包括在XxY网格中机器人从左上角到达右下角的不同走法计数,以及如何找到集合的所有非空子集。通过递归和迭代法解决这些问题,并提供了相关代码示例。同时讨论了字符串排列组合及数组中的魔术索引问题,提出高效解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、简单动态规划问题
1、机器人走方格I
     类似的参见《斐波那契数列》

   有一个XxY的网格,一个机器人只能走格点且只能向右或向下走,要从左上角走到右下角。请设计一个算法,计算机器人有多少种走法。

给定两个正整数int x,int y,请返回机器人的走法数目。保证x+y小于等于12。

    class Robot {
        // public int times = 0;
        // public int times1 = 0;

        /*** 递归解法 **/
        public int countWays1(int x, int y) {
            if (x < 0 || y < 0)
                return 0;
            if (x == 0 || y == 0)
                return 1;
            //     times1 ++;
            return countWays1(x - 1, y) + countWays1(x, y - 1);
        }

        /**  优化的递归解法 **/
        public int countWays(int x, int y) {
            if (x < 0 || y < 0)
                return 0;
            int[][] counts = new int[x + 1][y + 1];
            counts[0][0] = 1;
            return countWays(x, y, counts);
        }

        private int countWays(int x, int y, int[][] counts) {
            if (x < 0 || y < 0)
                return 0;
            if (counts[x][y] <= 0) {
                counts[x][y] = countWays(x - 1, y, counts) + countWays(x, y - 1, counts);
            //         times ++;
            }
            return counts[x][y];
        }
    }
2、Minimum Path Sum (矩阵路径最小和问题)(leetcode 65)
1)问题描述:

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

即给定一个m*n的数组矩阵,矩阵中所有值都是非负的;从左上角开始往右或者往下走,记录最终到达右下角的路径上所有元素之和的最小值问题;

2)问题分析:
简单的动态规划问题,记[i,j]位置元素的最小值为sum[i,j];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值