𝑰’𝒎 𝒉𝒉𝒈, 𝑰 𝒂𝒎 𝒂 𝒈𝒓𝒂𝒅𝒖𝒂𝒕𝒆 𝒔𝒕𝒖𝒅𝒆𝒏𝒕 𝒇𝒓𝒐𝒎 𝑵𝒂𝒏𝒋𝒊𝒏𝒈, 𝑪𝒉𝒊𝒏𝒂.
- 🏫 𝑺𝒉𝒄𝒐𝒐𝒍: 𝑯𝒐𝒉𝒂𝒊 𝑼𝒏𝒊𝒗𝒆𝒓𝒔𝒊𝒕𝒚
- 🌱 𝑳𝒆𝒂𝒓𝒏𝒊𝒏𝒈: 𝑰’𝒎 𝒄𝒖𝒓𝒓𝒆𝒏𝒕𝒍𝒚 𝒍𝒆𝒂𝒓𝒏𝒊𝒏𝒈 𝒅𝒆𝒔𝒊𝒈𝒏 𝒑𝒂𝒕𝒕𝒆𝒓𝒏, 𝑳𝒆𝒆𝒕𝒄𝒐𝒅𝒆, 𝒅𝒊𝒔𝒕𝒓𝒊𝒃𝒖𝒕𝒆𝒅 𝒔𝒚𝒔𝒕𝒆𝒎, 𝒎𝒊𝒅𝒅𝒍𝒆𝒘𝒂𝒓𝒆 𝒂𝒏𝒅 𝒔𝒐 𝒐𝒏.
- 💓 𝑯𝒐𝒘 𝒕𝒐 𝒓𝒆𝒂𝒄𝒉 𝒎𝒆:𝑽𝑿
- 📚 𝑴𝒚 𝒃𝒍𝒐𝒈: 𝒉𝒕𝒕𝒑𝒔://𝒉𝒉𝒈𝒚𝒚𝒅𝒔.𝒃𝒍𝒐𝒈.𝒄𝒔𝒅𝒏.𝒏𝒆𝒕/
- 💼 𝑷𝒓𝒐𝒇𝒆𝒔𝒔𝒊𝒐𝒏𝒂𝒍 𝒔𝒌𝒊𝒍𝒍𝒔:𝒎𝒚 𝒅𝒓𝒆𝒂𝒎
1-1: Description
地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?
示例 1:
输入:m = 2, n = 3, k = 1
输出:3
示例 2:
输入:m = 3, n = 1, k = 0
输出:1
提示:
1 <= n,m <= 100
0 <= k <= 20
通过次数211,920提交次数398,972
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1-2: Solution-DP
When I finished reading this question, my first thought was dynamic programming. We can use a 2-dim dp array to solve it. When the robot arrives at one coordinate. There will be two choices: down or right. So we can conclude the following formula:
// sum() function is to add each number in one position(i,j) e.g:sum(22,32) = 2+2+3+2
if(sum(i,j) <= k){
dp[i][j] = dp[i-1][j] or dp[i][j-1]
}
Here is my code:
public int movingCount(int m, int n, int k) {
boolean[][] dp = new boolean[m][n];
dp[0][0] = true;
int sum = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0 || sum(i, j) > k) {
continue;
}
if (i >= 1) {
dp[i][j] = dp[i][j] || dp[i - 1][j];
}
if (j >= 1) {
dp[i][j] = dp[i][j] || dp[i][j - 1];
}
if (dp[i][j]) {
sum++;
}
}
}
System.out.println(Arrays.deepToString(dp));
return sum;
}
public int sum(int i, int j) {
char[] sI = String.valueOf(i).toCharArray();
char[] sJ = String.valueOf(j).toCharArray();
int sum = 0;
for (char c : sI) {
sum += c - '0';
}
for (char c : sJ) {
sum += c - '0';
}
return sum;
}
public int get(int i) {
int result = 0;
while (i != 0) {
result += i % 10;
i = i / 10;
}
return result;
}
时间复杂度O(mn)
空间复杂度O(mn)
Notes:
You shouldn’t use dp[m+1][n+1] to simplify the initial process; Why? The sum(i,j)
function is related to position. If using dp[m+1][n+1], you will change the coordinate of the 2-dim array. Right? This is my mistake in solving this question.