Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 6, 2018 07:46
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/e770bbecbb3dc0ac9103009b3f98e179 to your computer and use it in GitHub Desktop.
Save jianminchen/e770bbecbb3dc0ac9103009b3f98e179 to your computer and use it in GitHub Desktop.
Number of path - using O(n) space instead of O(n^2) space, it took me more than 5 minutes to fix the bug - line 26
using System;
class Solution
{
public static int NumOfPathsToDest(int n) // 4
{
if( n <= 0) // false
{
return 0;
}
var previous = new int[n];
var current = new int[n];
for(int row = 0; row < n; row++ ) // horizontal
{
for(int col = 0; col < n; col++) // vertical
{
var firstRow = row == 0;
if(firstRow)
{
current[col] = 1;
}
else
{
current[col] = 0;
if(row <= col)
{
current[col] = previous[col] + current[col - 1];
}
}
}
for(int col = 0; col < n; col++)
{
previous[col] = current[col];
}
}
return current[n - 1];
}
static void Main(string[] args)
{
Console.WriteLine(NumOfPathsToDest(4));
}
}
/*
ok
https://www.linkedin.com/in/jianminchen/
time complexity O(n * n), space complexity is O(n * n), I can reduce space to O(n),
sure , let me reduce space complexity !
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