Created
January 6, 2018 07:04
-
-
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)
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 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