Pascal's Triangle II 求Pascal三角的某一行 @LeetCode

题目:

求Pascal三角的某一行


是前一题的follow up

http://blog.csdn.net/fightforyourdream/article/details/12867855


思路:

用了笨方法,基于前一题的结果,来取值。应该有用数学公式直接计算出来的办法。


package Level2;

import java.io.ObjectInputStream.GetField;
import java.util.ArrayList;

/**
 * Pascal's Triangle II 
 * 
 * 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?
 */
public class S119 {

	public static void main(String[] args) {
		System.out.println(getRow(0));
	}

	public static ArrayList<Integer> getRow(int rowIndex) {
		ArrayList<ArrayList<Integer>> list = generate(rowIndex+1);
		return list.size()==0 ? null : list.get(rowIndex);
    }
	
	private static ArrayList<ArrayList<Integer>> generate(int numRows) {
		ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
		int i, j;
		
		// i用来走列
        for(i=0; i<numRows; i++){
        	ArrayList<Integer> list = new ArrayList<Integer>();
        	// j用来走行,先走前半行
        	for(j=0; j<=i/2; j++){
        		if(j == 0){			// 对首位特殊处理
            		list.add(1);
            	}else if(i>0){		// 累加前面结果
            		list.add(ret.get(i-1).get(j-1)+ret.get(i-1).get(j));
            	}
        	}
        	// i再走后半行
        	for(; j<=i; j++){
        		if(j == i){		// 对末位特殊处理
        			list.add(1);
        		}else if(i>0){	// 累加前面结果
        			list.add(ret.get(i-1).get(j-1)+ret.get(i-1).get(j));
        		}
        	}
        	ret.add(list);
        }
        return ret;
    }
}



public class Solution {
    public ArrayList<Integer> getRow(int rowIndex) {
        ArrayList<Integer> old = new ArrayList<Integer>();
        ArrayList<Integer> cur = new ArrayList<Integer>();
        
        int i, j;
        for(i=0; i<=rowIndex; i++){
            for(j=0; j<i+1; j++){
                if(j == 0){
                    cur.add(1);
                }else if(j == i){
                    cur.add(1);
                }else{
                    cur.add(old.get(j-1)+old.get(j));
                }
            }
            old.clear();
            old.addAll(cur);
            cur.clear();
        }
        
        return old;
    }
}




你可能感兴趣的:(Pascal's Triangle II 求Pascal三角的某一行 @LeetCode)