leetcode题解-561. Array Partition I && 62. Unique Paths && 63. Unique Paths II

561,题目:

Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

Example 1:
Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4.
Note:
n is a positive integer, which is in the range of [1, 10000].
All the integers in the array will be in the range of [-10000, 10000].

本题是为了求一个最大最小值问题,看懂题目之后我们容易发现其实最终问题可以转化为将数组进行排序,然后各一个求和,因为为了使最后的和最大,我们需要让最大值和第二大值在一个数对里面,依次类推,只有这样才能使“资源浪费最少”。代码入下:

    public int arrayPairSum(int[] nums) {
        Arrays.sort(nums);
        int sum = 0;
        for(int i=0; i2){
            sum += nums[i];
        }
        return sum;
    }

62,题目:

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

本题就是寻找两点之间的不同路径数,因为机器人只可以向下和向右前进,所以我们可以按照列进行计算,可以归纳出每一列每个点的不同路径数是上一列对应点路径数加上本列上一个点路径数之和。如下所示:
1,1,1,1
1,2,3,4
1,3,6,10
1,4,10,20。。。
容易得出下面的代码,使用一个长度为m的数组记录每一列元素的路径数,进行迭代:

    public int uniquePaths(int m, int n) {
        int[] row = new int[m];
        for(int i=0; i1;
        for(int i=1; ifor(int j=1; j1] + row[j];
            }
        }
        return row[m-1];
    }

此外还可以通过数学归纳的方式得到每列最后一个元素的路径数,代码入下:

    public int uniquePaths1(int m, int n) {

        long result = 1;
        for(int i=0;i1,n-1);i++)
            result = result*(m+n-2-i)/(i+1);
        return (int)result;

    }

63,题目:

Follow up for "Unique Paths":

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.

[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
The total number of unique paths is 2.

Note: m and n will be at most 100.

本题在62的基础上加了一个障碍,即为1的元素被阻断,无法通过,使用和上面相同的思路,只不过对每个元素进行判断,如果为“1”则将该元素的路径数置0即可。代码入下:

    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int width = obstacleGrid[0].length;
        int[] dp = new int[width];
        dp[0] = 1;
        for (int[] row : obstacleGrid) {
            for (int j = 0; j < width; j++) {
                if (row[j] == 1)
                    dp[j] = 0;
                else if (j > 0)
                    dp[j] += dp[j - 1];
            }
        }
        return dp[width - 1];
    }

你可能感兴趣的:(leetcode刷题)