13 机器人的运动范围
描述
地上有一个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示例 1:
输入:m = 3, n = 1, k = 0
输出:1提示:
1 <= n,m <= 100
0 <= k <= 20来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
使用回溯法。目标就是从 (0,0) 这个点开始走,遍历完所有能走到的方格
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
if(threshold<0 || rows<0 || cols<0)return 0;
bool* visited = new bool[rows*cols];
memset(visited,0,rows*cols);
int count = move(threshold, rows, cols, visited,0,0);
delete[] visited;
return count;
}
//递归的终止条件是:不满足if终止递归,返回0
int move(int threshold, int rows, int cols, bool* visited, int row,int col)
{
int count = 0;
if(row>=0 && row<rows && col>=0 && col<cols
&& (computeBit(row, col)<=threshold) && visited[row*cols+col]==false) {
visited[row*cols+col]=true;
count = 1 + move( threshold, rows, cols, visited, row, col-1)
+ move( threshold, rows, cols, visited, row, col+1)
+ move( threshold, rows, cols, visited, row-1, col)
+ move( threshold, rows, cols, visited, row+1, col);
}
return count;
}
int computeBit( int row, int col)
{
return sumBit(row)+sumBit(col);
}
int sumBit(int n)
{
int sum = 0;
while(n){ //while(n>0)
sum+=(n%10);
n=n/10;
}
return sum;
}
};
14- I 剪绳子
描述
给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为 k[0],k[1]...k[m] 。请问 k[0]*k[1]*...*k[m] 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
示例 1:
输入: 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1示例 2:
输入: 10
输出: 36
解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36提示:
2 <= n <= 58
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jian-sheng-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
动态规划
class Solution {
public:
int cuttingRope(int n) {
if(n < 2)
return 0;
if(n == 2)
return 1;
if(n == 3)
return 2;
int* products = new int[n + 1];
products[0] = 0;
products[1] = 1;
products[2] = 2;
products[3] = 3;
int max = 0;
for(int i = 4; i <= n; ++i)
{
max = 0;
for(int j = 1; j <= i / 2; ++j)
{
int product = products[j] * products[i - j];
if(max < product)
max = product;
products[i] = max;
}
}
max = products[n];
delete[] products;
return max;
}
};