당신은 어떻게 ArrayLists
이 작동하는지 오해하고 실제로는 read the Javadoc해야합니다.
즉, 생성자의 매개 변수는 최대 크기가 아닌 메모리에있는 ArrayList의 초기 크기를 정의합니다. new ArrayList<Integer>(2)
을 인스턴스화하면 jvm이 두 개의 정수에 대해 충분한 공간을 할당하고 세 번째 요소를 추가하면 jvm이 더 많은 요소를 추가 할 수 있도록 ArrayList의 크기가 커진다는 것을 의미합니다.
또한이 위치에 요소가 추가 된 경우에만 get()
으로 ArrayList
위치에 액세스 할 수 있습니다.
마지막으로 특정 위치의 add
이 모든 요소를 오른쪽으로 이동한다는 것을 명심하십시오. 따라서 add(10,1)
다음에 add(2,4)
인 경우 첫 번째 추가가 오른쪽으로 이동합니다. 위로 질문에
, 당신이 절대적으로
ArrayList
아닌
array
을 사용하려는 경우, 당신은 올바른 위치에 다음, 당신의
ArrayList
적당한 크기로
set
값을 초기화해야합니다. 당신이 그것을 실행하는 경우
// the method with your algorithm which has been slightly modified
public static List<Integer> getRow(final int rowIndex) {
// notice that I call a helper method which initialises correctly the ArrayList
final List<Integer> list = init(rowIndex);
if (rowIndex == 1) {
// notice that I set the value at a given position
// I can only do it because I initialised all values to 0 first
list.set(0, 1);
} else {
final List<Integer> previousRowList = getRow(rowIndex - 1);
// again, I set values...
list.set(0, 1);
list.set(rowIndex - 1, 1);
for (int i = 1; i < (list.size() - 1); i++) {
// set again...
list.set(i, previousRowList.get(i - 1) + previousRowList.get(i));
}
}
// lets print out the row
System.err.println(list);
// then return it
return list;
}
public static List<Integer> init(final int size) {
// passing the size is overkill, but well...
final List<Integer> list = new ArrayList<Integer>(size);
// fill the ArrayList with zeros
for (int i = 0; i < size; i++) {
list.add(i, 0);
}
// then return it
return list;
}
public static void main(final String[] args) {
getRow(Integer.parseInt(args[0]));
}
당신이 (너무 좋지 않아,하지만 작업) 얻을 것이다 파스칼의 삼각형 : 여기
는 작업 솔루션입니다.11 행을 원할 경우 결과는 다음과 같습니다.
[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]
[1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1]
희망이 있습니다.
ArrayList "capacity"는 (예상되는) 성능 조정 목적을 제외하고는 부적합합니다. –
두 번째 명령문에서'list.add (0,1);'그리고'list.add (list.size() - 1,1);','list.size()'가 1 일 때 당신은 arraylist의 원소 0에 또 다른 "1"값을 넣습니다. –
('size()'는 arraylist 안의 원소의 수를 반환하지만 용량이 아니라 단지'add (index, value)'가 아닌 평범한'add (value)'를 사용하고 싶을 것이다. –