Created
January 6, 2018 07:46
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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