Perfect Squares
来源:互联网 发布:教育行业网络推广方案 编辑:程序博客网 时间:2024/06/05 11:22
问题:
Given a positive integer n
, find the least number of perfect square numbers (for example,1, 4, 9, 16, ...
) which sum to n.
样例
Given n = 12
, return 3
because 12 = 4 + 4 + 4
Given n = 13
, return 2
because 13 = 4 + 9
这个题目我们可以使用dp(动态规划来实现):
#include<iostream>#include <cmath>#include <algorithm>using namespace std;class Solution {public:/*** @param n a positive integer* @return an integer*/int numSquares(int n) {// Write your code hereint *dp = new int[n + 1];for (int i = 0; i < n + 1;i++){dp[i] = pow(2, 31) - 1;//将所有非平方数的结果置最大,保证之后比较的时候不被选中}//将所有平方数 置为1for (int i = 0; i*i < n + 1; i++){dp[i*i] = 1;}// 从小到大找任意数afor (int a = 0; a <= n; a++){// 从小到大找平方数bxbfor (int b = 0; a + b * b <= n; b++){// 因为a+b*b可能本身就是平方数,所以我们要取两个中较小的dp[a + b * b] = min(dp[a] + 1, dp[a + b * b]);}}return dp[n];}};int main(){int n = 0;cin >> n;Solution s;cout << s.numSquares(n) << endl;return 0;}
1 0
- Perfect Squares
- Perfect Squares
- Perfect Squares
- Perfect Squares
- Perfect Squares
- Perfect Squares
- Perfect Squares
- Perfect Squares
- Perfect Squares
- Perfect Squares
- Perfect Squares
- Perfect Squares
- Perfect Squares
- Perfect Squares
- Perfect Squares
- Perfect Squares
- Perfect Squares
- Perfect Squares
- android 音乐播放器
- DOM节点的类型及指针
- 防止 jsp被sql注入
- 文本聚类——Kmeans
- 如何在Caffe中配置每一个层的结构
- Perfect Squares
- linux内存寻址解析
- BZOJ-2462&&2351 矩阵模板&&Matrix 暴力 or Hash orAC自动机 or KMP
- Laravel--Facades门面
- 【读书笔记】《R语言实战》Day1
- PHP代码优化
- android基础课之Progress
- java毕向东听课笔记5(构造函数间的调用)
- 4种Java引用浅解