首页 > 其他 > 详细

Pascal's Triangle II

时间:2015-03-27 14:51:05      阅读:301      评论:0      收藏:0      [点我收藏+]

问题来源:https://leetcode.com/problems/pascals-triangle-ii/

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * <p>
 * ClassName PascalIsTriangleII
 * </p>
 * <p>
 * Description Given an index k, return the kth row of the Pascal‘s triangle.
 * 
 * For example, given k = 3, Return [1,3,3,1].
 * 
 * Note: Could you optimize your algorithm to use only O(k) extra space?
 * </p>
 * 
 * @author TKPad wangx89@126.com
 *         <p>
 *         Date 2015年3月27日 下午2:15:35
 *         </p>
 * @version V1.0.0
 *
 */
public class PascalIsTriangleII {
    public List<Integer> getRow(int rowIndex) {
        return generate(rowIndex + 1);
    }

    public List<Integer> generate(int numRows) {
        if (numRows <= 0) {
            return new ArrayList<Integer>();
        }
        List<Integer> temp = new ArrayList<Integer>();// 使用temp作为一个迭代器,来不断产生新的List
        temp.add(1);
        for (int i = 1; i < numRows; i++) {
            List<Integer> generateList = generateList(temp);
            temp = generateList;
        }
        return temp;
    }

    public List<Integer> generateList(List<Integer> temp) {
        int first = temp.get(0);
        ArrayList<Integer> al = new ArrayList<Integer>();
        al.add(first);
        for (int i = 1; i < temp.size(); i++) {
            al.add(first + temp.get(i));
            first = temp.get(i);
        }
        al.add(temp.get(0));
        return al;
    }

    public static void main(String[] args) {
        List<Integer> row = new PascalIsTriangleII().getRow(0);
        System.out.println(row);
    }
}

Pascal's Triangle II

原文:http://blog.csdn.net/shijiebei2009/article/details/44676247

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!