C#を使用して、指定された数のパスカルの三角形を生成するにはどうすればよいですか?
パスカルの三角形は、三角形の形をした数字のパターンです。パスカルの三角形には、組み合わせの計算に役立つ機能など、数学や統計に多くの用途があります。
三角形の各数字は、その上の2つの数字の合計です。たとえば、4行目-上の行の3と3の合計です。行の最初と最後の数字は常に1になります。
時間計算量 − O(N)
スペースの複雑さ − O(N)
例
public class Arrays{
public List<List<int>> GeneratePascal(int n){
List<List<int>> res = new List<List<int>>();
if (n <= 0){
return null;
}
List<int> first = new List<int>();
first.Add(1);
res.Add(first);
if (n == 1){
return res;
}
for (int i = 2; i < n; i++){
List<int> prev = res.LastOrDefault();
List<int> cur = new List<int>();
for (int temp = 0; temp < i; temp++){
cur.Add(1);
}
for (int j = 1; j < i - 1; j++){
cur[j] = prev[j - 1] + prev[j];
}
res.Add(cur);
}
return res;
}
}
static void Main(string[] args){
Arrays s = new Arrays();
var res = s.GeneratePascal(5);
} 出力
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
-
NumPyを使用して、特定のリスト内の数値の倍数を検索する
このプログラムでは、与えられた数の倍数が存在するインデックス位置を見つけます。このタスクには、NumpyライブラリとPandasライブラリの両方を使用します。 アルゴリズム Step 1: Define a Pandas series. Step 2: Input a number n from the user. Step 3: Find the multiples of that number from the series using argwhere() function in the numpy library. サンプルコード import numpy as np listnum
-
Pythonを使用して特定の数値の桁数を見つける方法は?
このプログラムでは、ユーザーが指定した整数の桁数を見つける必要があります。 例 ユーザー入力:123、出力:3 ユーザー入力:1987、出力:4 アルゴリズム Step 1: Take Integer value as input value from the userStep 2: Divide the number by 10 and convert the quotient into Integer typeStep 3: If quotient is not 0, update count of digit by 1Step 4: If quotient is 0, stop