条件:
- 当前所在格子的下标组成的数字之和不大于K
- 不能超出格子
思路一:
直接遍历整个数组,统计所有满足条件的格子,但是这样的时间复杂度为O(n*m);
思路二:
当前所在的格子的下标组成的数字之和如果刚好等于K,那么不用往右边搜索,也不用网下方搜索,这样就能节省时间。
具体做法:
当前格子满足条件?
是:统计+1,然后将当前格子入栈,往右走一步
否:出栈,往下走一步
循环上述过程,直到栈为空
import java.util.Stack;
class Point
{
private int x=0,y=0;
public Point(int x,int y)
{
this.x=x;
this.y=y;
}
public int getIdx()
{
return this.x;
}
public int getIdy()
{
return this.y;
}
}
class Solution {
public boolean fun(int idx,int idy,int m,int n,int K) //判断下标是否符合要求
{
if(idx>=0&&idy>=0&&idx<m&&idy<n)
{
int xt=0,yt=0;
do
{
xt=xt+idx%10;
idx=idx/10;
}while(idx!=0);
do
{
yt=yt+idy%10;
idy=idy/10;
}while(idy!=0);
if(xt+yt<=K)
return true;
else
return false;
}
else
return false;
}
public int movingCount(int m,int n,int k)
{
int count=0;
Stack<Point> s=new Stack<Point>();
s.push(new Point(0,0));
int idx=0,idy=0;
do
{
if(this.fun(idx,idy,m,n,k))
{
s.push(new Point(idx,idy));
count+=1;
idx=idx+1;//往右走
}
else
{
Point p=s.pop();
idx=p.getIdx();
idy=p.getIdy()+1;//往下走
}
}while(!s.empty());
return count;
}
public static void main(String[] args)
{
Solution s=new Solution();
System.out.print(s.movingCount(2,3,1));
}
}
剪绳子
动态规划法:
public class 剪绳子 {
public static int maxAfterCutting(int length) {
if (length < 2) {
return 0;
}
if (2 == length) {
return 1;
}
if (3 == length) {
return 2;
}
int[] products = new int[length + 1]; // 将最优解存储在数组中
// 数组中第i个元素表示把长度为i的绳子剪成若干段之后的乘积的最大值
products[0] = 0;
products[1] = 1;
products[2] = 2;
products[3] = 3;
int max = 0;
for (int i = 4; i <= length; i++) { //i表示长度
max = 0;
for (int j = 1; j <= i / 2; j++) { //由于长度i存在(1,i-1)和(i-1,1)的重复,所以只需要考虑前一种
int product = products[j] * products[i - j];
if (product > max) {
max = product;
}
}
products[i] = max;
}
return products[length];
}
}
时间复杂度:O(n^2)。