zoukankan      html  css  js  c++  java
  • 【leetcode】Perfect Squares (#279)

    Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16 ...) which sum to n. For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

    解析:

    利用动态规划解决此问题:对于要求的当前节点而言都是从前面的节点转移过来的,只是这些转移节点并非一个,而是多个,比如1*1,2*2,3*3,,,那么相应的res[i-1]、res[i-4]、res[i-9]等等都是转移点。从这些候选项中找到最小的那个,然后加1即可。

     

    算法实现代码:

    //#include "stdafx.h"
    #include <iostream>
    #include <cstdio>
    #include <climits>
    #include <ctime>
    #include <algorithm>
    #include <vector>
    #include <stack>
    #include <queue>
    #include <cstdlib>
    #include <windows.h>
    #include <string>
    #include <cstring>
    #include <cmath>
    
    using namespace std;
    
    class Solution {
    public:
        int numSquares(int n) {
            vector<int> res(n + 1);
            for (int i = 0; i <= n; ++i){
                res[i] = i;
                for (int j = 1; j * j <= i; ++j){
                    res[i] = min(res[i - j * j] + 1, res[i]);
                }
            }
            return res[n];
        }
    };
    
    int main(){
    	Solution s;
    	cout<<s.numSquares(13);
    	return 0;
    }
    

      

  • 相关阅读:
    关闭caffe日志输出
    学习与工作中的认真和不认真
    深度学习_吴恩达_简单笔记
    JavaSE、JavaEE和JavaME的区别
    teamviewer
    提高深度学习检测网络准确率方法_未完待续
    提高深度学习分类模型准确率方法
    jQuery图片提示示例
    jQuery简单导航示例
    css盒子模型
  • 原文地址:https://www.cnblogs.com/dragonir/p/6189443.html
Copyright © 2011-2022 走看看