• Leetcode279. 完全平方数


    问题描述

    给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。

    示例

    示例 1:
    输入: n = 12
    输出: 3
    解释: 12 = 4 + 4 + 4.
    示例 2:
    输入: n = 13
    输出: 2
    解释: 13 = 4 + 9.

    代码

    DP

    递归不太行,就用了DP

    class Solution {
        public int numSquares(int n) {
    		  Stack<Integer> queue=new Stack<Integer>();
    		 int[] arr=new int[n+1];
    		 	int x=1,i=2;
    		 	while(x<=n) {
    		 		queue.add(x);
    		 		x=i*i;
    		 		i++;
    		 	}
    		 	int min=n;
    		 		for(int j=1;j<n+1;j++) {
    		 		arr[j]=j;
    		 		for(int m=0;m<queue.size();m++) {
    		 			if(queue.get(m)<=j)
    		 				arr[j]=Math.min(arr[j], arr[j-queue.get(m)]+1);
    		 			else
    		 				break;
    		 		}
    		 	}
                 return arr[n];
    	 }
    }
    

    贪心枚举

    class Solution {
        Set<Integer> square_nums = new HashSet<Integer>();
    
    	  protected boolean is_divided_by(int n, int count) {
    	    if(count==1)
    	    	return square_nums.contains(n);
    	    for(Integer num:square_nums) {
    	    	if(n>num&&is_divided_by(n-num, count-1))
    	    		return true;
    	    }
    	    return false;
    	  }
    
    	  public int numSquares(int n) {
    		  square_nums.clear();
    		  for(int i=1;i*i<=n;i++) {
    			  square_nums.add(i*i);
    		  }
    		  int count=1;
    		  for(;count<=n;count++) {
    			  if(is_divided_by(n, count))
    				  return count;
    		  }
    		  return n;
    	  }
    }
    

  • 相关阅读:
    信号、事件与状态
    信号处理机制的范式分析
    三寒两倒七分饱
    血热的人吃什么好
    消息、信息与信号的区别
    Busy waiting
    事件的处理机制:单播、广播、链式路由、职责链。
    事件处理:pull与push
    响应式编程
    类、组件、人机交互
  • 原文地址:https://www.cnblogs.com/code-fun/p/14311255.html
Copyright © 2020-2023  润新知