Skip to content

Instantly share code, notes, and snippets.

@Mastersam07
Last active March 31, 2020 09:50
Show Gist options
  • Select an option

  • Save Mastersam07/cd47cbb4d2c9aafa7b2a4d9b1d7f1708 to your computer and use it in GitHub Desktop.

Select an option

Save Mastersam07/cd47cbb4d2c9aafa7b2a4d9b1d7f1708 to your computer and use it in GitHub Desktop.
pascal triangle
// pascal triangle
void main() {
print(pascalTriangle(5)); // [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
print("--------------------------");
print(pascalTriangle(1)); // should return 1
print("--------------------------");
print(pascalTriangle(0)); // should return empty []
print("--------------------------");
print(pascalTriangle(-6)); // should return -1
}
List<List<int>> pascalTriangle(int n) { // where n is number of rows
List<List<int>> triangle = []; // initialize so [] can be returned when rows == 0
if (n<0){
triangle=[[-1]]; // where we input negative number returns -1
}
for (var row = 0; row < n; row++) {
List<int> currentRow = [1]; // initialize current row such that return [1] when row == 1
if (row >= 2) { // when row is from 2 upwards
for (var j = 0; j < triangle[row - 1].length - 1; j++) {
currentRow.add(triangle[row - 1][j] + triangle[row - 1][j + 1]);
}
}
if (row >= 1) {
currentRow.add(1);
}
triangle.add(currentRow);
}
return triangle;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment