Check Pascal's Triangle
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (numRows < 1) return result;
if (numRows == 1) {
List<Integer> currList = new ArrayList<Integer>();
currList.add(1);
result.add(currList);
return result;
}
List<List<Integer>> lastResult = generate(numRows-1);
result.addAll(lastResult);
List<Integer> lastList = lastResult.get(lastResult.size() - 1);
List<Integer> newList = new ArrayList<Integer>();
newList.add(1);
for (int i=0; i<lastList.size()-1; i++) {
newList.add(lastList.get(i) + lastList.get(i+1));
}
newList.add(1);
result.add(newList);
return result;
}
No comments:
Post a Comment