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;
}
};