Project Euler 15 solution

Lattice paths

Problem 15

Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.

How many such routes are there through a 20×20 grid?

Link: https://projecteuler.net/problem=15 

My solution:

Using recursie function to find out the routes.

Implemented by Lu.Qian. using C++:

 1 #include <iostream>
 2 //#include <cstring>
 3 //#include <cmath>
 4 //#include <map>
 5 using namespace std;
 6 
 7 unsigned long long int num = 0;
 8 void find_route(int len, int wid){
 9     if(len == 0 || wid == 0){
10         num++;
       return;
11 } 12 find_route(len - 1, wid); 13 find_route(len, wid - 1); 14 } 15 16 int main() 17 { 18 19 find_route(20,20); 20 cout<<num<<endl; 21 return 0; 22 }

However, this project I worte will take so much cost on recurive funciton, and the running time it take will be unacceptable.

So I'll wirite another function by using simple iteration. 

 I implemented it by python and usd a container 'dict' to eliminate duplicate computating.

 1 c = {}
 2 def countRoutes(m,n):
 3     if n == 0 or m == 0:
 4         return 1
 5 
 6     if c.has_key((m,n)):
 7         return c[(m,n)]
 8 
 9     c[(m,n)] = countRoutes(m, n-1) + countRoutes(m-1,n)
10     return c[(m,n)]

The iterative solution is also using container (two-dimensional array) to fulfill the container from bottom to up.

Here is the pseudocode for iterative solution:

function countRoutes(m,n)
    grid array[m + 1][n + 1] // A two-dimensional 0-indexed array of           size m + 1 by n + 1
    for i = 0 to m do
        grid[i][0] 1
    end for
    for j = 0 to n do
        grid[0][j] 1
    end for
    for i = 1 to m do
        for j = 1 to n do    
            grid[i][j] grid[i − 1][j] + grid[i][j − 1]
        end for
    end for
    return grid[m][n]
end function            
View Code

This problem has another approach to solve - combinatorial solution. This gives us a much faster O(n) solution.

Acknowledgement:

All the algorithms which give O(mn) or O(n) are from Pim Spelier's work.

转载于:https://www.cnblogs.com/QianL/p/5688720.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值