关于java:LeetCode119杨辉三角-II

7次阅读

共计 972 个字符,预计需要花费 3 分钟才能阅读完成。

杨辉三角 II

题目形容:给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例阐明请见 LeetCode 官网。

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl…
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法一:暴力破解法

首先,当 numRows 等于 0 或者 1 时,间接返回固定的前两行;

当 numRows 大于等于 2 时,从第 2 行开始解决,如果以后行是 cur,上一行是 last:

  • cur 的第一个数字是 1;
  • cur 的第二个数字到倒数第二个数字 (j) 是 last 行的相应地位 (j- 2 和 j -1) 的和;
  • cur 的最初一个数字是 1;
  • 将 last 设置为 cur。

最初返回 cur。

备注:办法跟该题 LeetCode-118- 杨辉三角 齐全一样。

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

public class LeetCode_119 {public static List<Integer> getRow(int rowIndex) {List<Integer> one = new ArrayList<>();
        one.add(1);
        if (rowIndex == 0) {return one;}
        List<Integer> two = new ArrayList<>();
        two.add(1);
        two.add(1);
        if (rowIndex == 1) {return two;}
        List<Integer> last = two;
        List<Integer> cur = new ArrayList<>();
        for (int i = 2; i <= rowIndex; i++) {cur = new ArrayList<>();
            cur.add(1);
            for (int j = 1; j < i; j++) {cur.add(last.get(j - 1) + last.get(j));
            }
            cur.add(1);
            last = cur;
        }
        return cur;
    }

    public static void main(String[] args) {for (Integer integer : getRow(3)) {System.out.print(integer + " ");
        }
    }
}

【每日寄语】愿你所得过少时,不会终日愤愤;愿你所得过多时,不用终日惶恐。

正文完
 0