1. 机器人的运动范围
1.1 题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
1.2 示例1
输入
5,10,10
返回值
21
1.3 核心代码实现
public class Solution {
public int movingCount(int threshold, int rows, int cols){
boolean[] flag = new boolean[rows * cols]; //标记是否访问过某格
return movingCountCore(threshold, rows, cols, 0, 0, flag);
}
public int movingCountCore(int threshold, int rows, int cols, int x, int y, boolean[] flag){
if(x < 0 || x >= rows || y < 0 || y >= cols) return 0;
if(!flag[x * cols + y] && check(x) + check(y) <= threshold){
flag[x * cols + y] = true; //符合题目要求,flag改为true
return 1 + movingCountCore(threshold, rows, cols, x - 1, y, flag)
+ movingCountCore(threshold, rows, cols, x + 1, y, flag)
+ movingCountCore(threshold, rows, cols, x, y - 1, flag)
+ movingCountCore(threshold, rows, cols, x, y + 1, flag);
}
return 0;
}
private int check(int n){
//用于判断是否符合阈值范围
int sum = 0;
while(n > 0){
sum += (n % 10);
n /= 10;
}
return sum;
}
}
2. 构建乘积数组
2.1 题目描述
给定一个数组A[0,1,…,n-1],请构建一个数组B[0,1,…,n-1],其中B中的元素B[i]=A[0]A[1]…*A[i-1]A[i+1]…*A[n-1]。不能使用除法。(注意:规定B[0] = A[1] * A[2] * … * A[n-1],B[n-1] = A[0] * A[1] * … * A[n-2];)
对于A长度为1的情况,B无意义,故而无法构建,因此该情况不会存在。
2.2 示例1
输入
[1,2,3,4,5]
返回值
[120,60,40,30,24]
2.3 核心代码实现
//将B[i]拆为两部分乘积,B[i] = (A[0]*A[1]*……*A[i-1])*(A[i+1]*……*A[n-1])
import java.util.ArrayList;
public class Solution {
public int[] multiply(int[] A) {
int len = A.length;
int[] B = new int[len];
B[0] = 1;
for(int i = 1; i < len; i++){
B[i] = B[i - 1] * A[i - 1]; //左边
}
int right = 1;
for(int i = len - 2; i >= 0; i--){
right *= A[i + 1]; //右边
B[i] *= right; //左边*右边
}
return B;
}
}