• 刷题279. Perfect Squares


    一、题目说明

    题目279. Perfect Squares,给定一个正整数n,找到m个数其平方和刚好是n。求m的最小值,难度是Medium!

    二、我的解答

    bfs算法:

    class Solution{
    	public:
    		//bfs
    		int numSquares(int n){
    			queue<int> q;
    	        q.push(n);
    	        int sum=0;
    	        while(1){
    	            int l=q.size();
    	            for(int i=0;i<l;i++){
    	                int f=q.front();
    	                if(f==0) return sum;
    	                for(int i=1;i*i<=f;i++) {
    	                    if(f-i*i==0) return sum+1;
    	                    q.push(f-i*i); 
    	                };
    	                q.pop();
    	            }
    	            sum++;
    	        }
    		}
    };
    

    性能如下:

    Runtime: 132 ms, faster than 42.52% of C++ online submissions for Perfect Squares.
    Memory Usage: 53.2 MB, less than 5.77% of C++ online submissions for Perfect Squares.
    

    优化:

    class Solution{
    	public:
    		//bfs
    		int numSquares(int n){
            	queue<int> q;
    	        q.push(n);
    	        int level = 0;
    	        vector<bool> visit(n + 1, false);
    	        while(!q.empty())
    	        {
    	            int size = q.size();
    	            level++;
    	            for(int i = 0; i < size; i++)
    	            {
    	                int temp = q.front();
    	                q.pop();
    	                visit[temp] = true;
    	                for(int i = 1; i * i <= temp; i++)
    	                {
    	                    if(temp == i * i) return level;
    	                    if(!visit[temp - i * i]) q.push(temp - i * i);
    	                }
    	            }
    	        }
    	        return level; 
    		}
    };
    
    Runtime: 124 ms, faster than 46.86% of C++ online submissions for Perfect Squares.
    Memory Usage: 29.7 MB, less than 11.54% of C++ online submissions for Perfect Squares.
    

    三、优化措施

    dp:

    class Solution{
    	public:
    		int numSquares(int n){
    			vector<int> dp(n+1);
    			for(int i=1;i<=n;i++){
    				dp[i] = i;
    			}
    			for(int i=2;i<=n;i++){
    				for(int j=1;j*j<=i;j++){
    					dp[i] = min(dp[i],dp[i-j*j]+1);
    				}
    			}
    			return dp[n];
    		}
    };
    

    性能如下:

    Runtime: 108 ms, faster than 58.71% of C++ online submissions for Perfect Squares.
    Memory Usage: 11.4 MB, less than 61.54% of C++ online submissions for Perfect Squares.
    
    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    javaScript第一篇
    数据结构与算法学习笔记2018-01-30
    各种编程技术文章收集链接
    git最简单直接粗爆与github教程
    Word2Vec原理之Negative Sample
    Word2Vec原理之层次Softmax算法
    统计语言模型
    各种优化方法总结比较(sgd/momentum/Nesterov/adagrad/adadelta)
    TensorBoard:可视化学习
    Batch Normalization
  • 原文地址:https://www.cnblogs.com/siweihz/p/12294766.html
Copyright © 2020-2023  润新知