条件:
- 格子組成物がK以下である現在のインデックス番号
- あなたは、グリッドを超えることはできません。
アイデア:
Directは、すべてのグリッドの条件を満足カウント、配列全体を横断するが、この時間の複雑さはO(N * M)です。
2思考:
あなたが時間を節約することができるように、インデックスのデジタルグリッドが現在位置していると組成が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)。