1回のループでパスカルの三角形を書くことはできますか? 複数のループを使用して記述しましたが、正常に動作しています。
2052 次
2 に答える
1
一体、私は私のコメントを答えにします:
ヒントとして、作成する三角形の行数を入力として受け取るメソッドを作成し、メソッドの開始時に、これが変換される項目の総数を計算してから、for ループ ループを作成します。すべてのアイテムを通して。ループ内では、現在の行と列を簡単に計算し、この情報を使用してアイテムの値を作成できます。
于 2012-04-22T14:36:58.367 に答える
0
欲しいコードはこちら
また
package net.yogesh.test;
import java.util.ArrayList;
import java.util.List;
public class pascal3 {
public static void main(String[] args) {
int noOfRows = 10;
int counter = 1;
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list = itMe(list, counter,noOfRows);
}
public static List<Integer> itMe(List<Integer> list, int counter,int noOfRows) {
System.out.println(list);
List<Integer> tempList = new ArrayList<Integer>();
tempList.add(1);
for (int i = 1; i < list.size(); i++) {
tempList.add(list.get(i) + list.get(i-1));
}
tempList.add(1);
if(counter != noOfRows)
itMe(tempList, ++counter,noOfRows);
return tempList;
}
}
ノート
ここで出力は期待どおりです
ただし、フォーマットされたビューが必要な場合は、余分なループを使用する必要があります。
出力
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
于 2012-04-22T14:47:02.190 に答える