Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 6, 2018 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/97d920a510143036965ee6dd3bc756e3 to your computer and use it in GitHub Desktop.
Save jianminchen/97d920a510143036965ee6dd3bc756e3 to your computer and use it in GitHub Desktop.
Number of path - need to work on the space complexity lower to O(n)
using System;
class Solution
{
public static int NumOfPathsToDest(int n) // 4
{
if( n <= 0) // false
{
return 0;
}
var path = new int[n, n];
for(int row = 0; row < n; row++ ) // horizontal
{
for(int col = 0; col < n; col++) // vertical
{
var firstRow = row == 0;
if(firstRow)
{
path[0, col] = 1;
}
else
{
if(row <= col)
{
path[row, col] = path[row - 1, col] + path[row, col - 1];
}
}
}
}
return path[n-1, n-1];
}
static void Main(string[] args)
{
Console.WriteLine(NumOfPathsToDest(4));
}
}
/*
x x x x 14
x x x 5 14 n = 4, output is 5
x x 2 5 9
x 1 2 3 4
1 1 1 1 1 1 -> go to right, only one way to go to right
go to first row,
1 1 1 1 1
and then go to second row
x 1 2 3 4
because it is the sum of left and down - arr[i, j] = arr[i - 1, j] + arr[i, j - 1] if i <= j
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment