ArrayEasyFinish

(1)Plus One

解题思路:模拟现实中做加法的方式,在个位加一,并考虑进位的情况。代码如下:

 1 public class Solution {
 2     public int[] plusOne(int[] digits) {
 3         int carries = 1;
 4         for (int i = digits.length - 1; i >= 0 && carries > 0; i--) {
 5             int sum = digits[i] + carries;
 6             digits[i] = sum % 10;
 7             carries = sum / 10;
 8         }
 9         if (carries == 0) {
10             return digits;
11         }
12         int[] result = new int[digits.length + 1];
13         result[0] = 1;
14         for (int i = 1; i < result.length; i++) {
15             result[i] = digits[i - 1];
16         }
17         return result;
18     }
19 }

(2)Pascal‘s Triangle

解题思路:从示例可以看出规律:(i,j)处的值等于(i-1,j-1)和(i-1,j)处的值之和。

代码如下【应该不是最优解】:

 1 public class Solution {
 2     public List<List<Integer>> generate(int numRows) {
 3         List<List<Integer>> triangle = new ArrayList<List<Integer>>();
 4         if (numRows <=0){
 5             return triangle;
 6         }
 7         for (int i=0; i<numRows; i++){
 8             List<Integer> row =  new ArrayList<Integer>();
 9             for (int j=0; j<i+1; j++){
10                 if (j==0 || j==i){
11                     row.add(1);
12                 } else {
13                     row.add(triangle.get(i-1).get(j-1)+triangle.get(i-1).get(j));
14                 }
15             }
16             triangle.add(row);
17         }
18         return triangle;
19     }
20 }

(3)Pascal‘s Triangle II

时间: 2024-10-07 13:22:58

ArrayEasyFinish的相关文章