Cranking the Coding Interview: Recursion and Dynamic Programming

Triple Step

有个小孩正在上楼梯,楼梯有n阶台阶,小孩一次可以上1阶、2阶、3阶。请实现一个方法,计算小孩有多少种上楼的方式。为了防止溢出,请将结果Mod 1000000007

给定一个正整数int n,请返回一个数,代表上楼的方式数。保证n小于等于100000。

测试样例:
1

返回:1

代码实现:

class GoUpstairs {
public:
    int countWays(int n) {
        vector<long long int> res(n+1, 0);
        res[1] = 1; res[2] = 2; res[3] = 4;
        for(int i = 4; i <= n; i ++) {
            res[i] = res[i-3] + res[i - 2] + res[i - 1];
            res[i] %= 1000000007;
        }    
        return res[n]; 
    }
};

如果不使用long long int的话,那么可以这样做:

class GoUpstairs {
public:
    int countWays(int n) {
        vector<int> res(n+1, 0);
        res[1] = 1; res[2] = 2; res[3] = 4;
        for(int i = 4; i <= n; i ++) {
            res[i] = (res[i-3]%1000000007 + res[i - 2]%1000000007)%1000000007 + res[i - 1]%1000000007;
            res[i] %= 1000000007;
        }    
        return res[n]; 
    }
};

Robot in a Grid

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

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

测试样例:
2,2

返回:2

代码实现:使用DFS就可以搞定。

class Robot {
public:
    void BackTracking(int& res, int x, int y, int stt_x, int stt_y) {
        if(stt_x > x || stt_y > y) return;
        if(stt_x == x && stt_y == y) { res++; return; }
        BackTracking(res, x, y, stt_x+1, stt_y);
        BackTracking(res, x, y, stt_x, stt_y+1);
    }

    int countWays(int x, int y) {
        if(x + y > 12) return 0;
        int res = 0, stt_x = 1, stt_y = 1; 
        BackTracking(res, x, y, stt_x, stt_y);
        return res;
    }
};

Magic Index

在数组A[0..n-1]中,有所谓的魔术索引,满足条件A[i]=i。给定一个升序数组,元素值各不相同,编写一个方法,判断在数组A中是否存在魔术索引。请思考一种复杂度优于o(n)的方法。
给定一个int数组A和int n代表数组大小,请返回一个bool,代表是否存在魔术索引。

测试样例:
[1,2,3,4,5]

返回:false

代码实现:

最简单的暴力方法,不过不符合要求。

class MagicIndex {
public:
    bool findMagicIndex(vector<int> A, int n) {
        // write code here
        for(int i = 0; i < n; i++)
            if(i == A[i]) return true;
        return false;
    }
};

使用夹逼的方法从两边向中间逼近,那么复杂度其实是减少了一半:

class MagicIndex {
public:
    bool findMagicIndex(vector<int> A, int n) {
        int stt = 0, lst = n - 1;
        while(stt < lst) {
            if(A[stt] == stt || A[lst] == lst) return true;
            stt++; lst--;
        }
        return false;
    }
};

二分法的迭代:

class MagicIndex {
public:
    bool findMagicIndex(vector<int> A, int n) {
        int stt = 0, lst = n - 1, mid = 0;
        while(stt < lst) {
            mid = (stt+lst) >> 1;
            if(mid == A[mid]) return true;
            else if(mid < A[mid])  lst = mid;
            else  stt = mid + 1;    
        }
        return false;
    }
};

递归的做法:

class MagicIndex {
private:
    bool magic(vector<int> A, int stt, int lst){
        if(stt >= lst) return false;
        int mid = (stt + lst) >> 1;
        if(mid == A[mid]) return true;
        else if(mid > A[mid]) return magic(A, mid + 1, lst);
        else return magic(A, stt, mid);
    }
public:
    bool findMagicIndex(vector<int> A, int n) {
        if(n == 0) return true;
        else return magic(A,0,n);
    }
};

Robot II

有一个XxY的网格,一个机器人只能走格点且只能向右或向下走,要从左上角走到右下角。请设计一个算法,计算机器人有多少种走法。注意这次的网格中有些障碍点是不能走的。

给定一个int[][] map(C++ 中为vector >),表示网格图,若map[i][j]为1则说明该点不是障碍点,否则则为障碍。另外给定int x,int y,表示网格的大小。请返回机器人从(0,0)走到(x - 1,y - 1)的走法数,为了防止溢出,请将结果Mod 1000000007。保证x和y均小于等于50

法一:使用BFS计算。超时了!

class Robot {
public:
    int m, n;
    void findNumPath(int& res, vector<vector<int> > map, int x, int y, int r_x, int r_y) {
        if(r_x > x || r_y > y) return;
        if(r_x == x && r_y == y) { res++; res %= 1000000007; return; }
        if(r_x < n && r_y < m && map[r_y][r_x]) {
            findNumPath(res, map, x, y, r_x + 1, r_y);
            findNumPath(res, map, x, y, r_x, r_y + 1);
        }
    }

    int countWays(vector<vector<int> > map, int x, int y) {
        if(x > 50 || y > 50) return 0;
        int res = 0, r_x = 0, r_y = 0;
        m = map.size(), n = m?map[0].size():0;
        findNumPath(res, map, x - 1, y - 1, r_x, r_y);
        return res;
    }
};

法二:使用动态规划计算

class Robot {
public: 
    int countWays(vector<vector<int> > map, int x, int y) {
        int res = 0, r_x = 0, r_y = 0;
        int m = map.size(), n = m?map[0].size():0;
        if(x > 50 || y > 50 || x < 0 || y < 0 || !m) return res;

        bool block = false;
        block = map[0][0]?false:true;
        for(int row = 1; row < x; row++) {
            if(!map[row][0]) block = true;  
            else  map[row][0] = block?0:1;    
        }    
        block = map[0][0]?false:true;
        for(int col = 1; col < y; col++) {
            if(!map[0][col]) block = true;  
            else map[0][col] = block?0:1;           
        }

        for(int row = 1; row < x; row++) {
            for(int col = 1; col < y; col++) {
                if(!map[row][col]) map[row][col] = 0;
                else map[row][col] = map[row][col-1] + map[row-1][col];
            }
        }
        if(y < 1 || x < 1) return res;
        return map[x-1][y-1];
    }
};

N queen

牛客网上这道题目我觉得有问题,n皇后问题居然是对角线。

应该是皇后所在的斜线。

检测一个是否为n皇后,只需要检测最近加入的皇后与之前的皇后会不会发生冲突。

实现的代码:

class Queens {
public:
    bool isNQueue(vector<vector<int>>& q, int n) {
        int m = q[0].size(); 
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(q[i][j]) { // down and to down right direction 
                    for(int down = i + 1; down < n; down++) if(q[down][j]) return false;
                    for(int row = i+1, col = j + 1; row < n && col < m; row++, col++) if(q[row][col]) return false;
                }
            }
        }
        return true;
    }

    void backTracking(int& res, vector<vector<int>>& chess, int stt, int n) {
        if(stt == n) {
            if(isNQueue(chess, stt)) res++;
            return;
        }    
        for(int i = 0; i < n; i++) {
            if(isNQueue(chess, stt)) {
                chess[stt][i] = 1;
                if(isNQueue(chess, stt+1)) 
                    backTracking(res, chess, stt+1, n);
                chess[stt][i] = 0;
            }
        }
    }

    int nQueens(int n) {
        if(n == 0) return 0;
        vector<vector<int> > chess(n, vector<int>(n, 0));
        int res = 0, stt = 0;
        backTracking(res, chess, stt, n);
        return res;
    }
};

使用普通的递归实现为:

class Queens {
public:
    int nQueens(int n) {
        int count=0;
        int *a=new int[n+1];
        Queens1(a,1,n,count);
        return count; 
    }

    void Queens1(int a[], int i, int n, int &count){
        if(i>n){
            count++; return;
        }
        for(int j=1;j<=n;j++){
            a[i]=j;
            if(Place(a,i))
                Queens1(a,i+1,n,count);
        }
    }

    bool Place(int *a,int i){
        for(int j=1;j<i;j++)
            if((a[j]==a[i])||(a[j]-a[i]==(j-i))||(a[j]-a[i]==i-j))  return false;
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值