Robot range of motion

Here Insert Picture Description
condition:

  • The current index number where lattice composition is not greater than K
  • You can not exceed the grid

An idea:
Direct traverse the entire array, count all satisfy the conditions of the grid, but this time complexity is O (n * m);

Thinking two:
digital grid of the index is currently located and if the composition is exactly equal to K, then do not search to the right, it does not mesh below the search, so you can save time.
Specifically:
the current grid to meet the conditions?
Are: statistical +1, then the current cell stack, right, go one step
No: pop, go down step by
circulating the process until the stack is empty

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

Cut the rope

Here Insert Picture Description
Dynamic Programming:

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

Time complexity: O (n ^ 2).

Published 16 original articles · won praise 1 · views 1253

Guess you like

Origin blog.csdn.net/cf1169983240/article/details/104399623