题目:
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
给你一个整数 n ,返回和为 n 的完全平方数的 最少数量 。
完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如,1、4、9 和 16 都是完全平方数,而 3 和 11 不是。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/perfect-squares
方法一(常规方法):动态规划
状态转移方程:ƒ[i] = 1 + [√i] min j=1 ƒ[i-j2]
1 public int numSqu(int n){ 2 int [] f = new int [n+1]; 3 for (int i=1; i <=n;i++){ 4 int minn = Integer.MAX_VALUE; 5 for(int j = 1; j * j <= i ; j++){ 6 minn = Math.min(minn,f[i - j * j]); 7 } 8 f[i] = minn + 1; 9 } 10 return f[n]; 11 } 12 }
方法二:用数学定理来简化
利用四平方和定理来快速筛选答案
当n≠4k x (8m+7)时,我们需要判断到底多少个完全平方数能够表示 n,我们知道答案只会是 1,2,3中的一个:
答案为 1 时,则必有 n 为完全平方数,这很好判断;
答案为 2 时,则有 n=a2+b2,我们只需要枚举所有的a(1≤a≤√n),判断 n-a2是否为完全平方数即可;
答案为 3 时,我们很难在一个优秀的时间复杂度内解决它,但我们只需要检查答案为 1或 2 的两种情况,即可利用排除法确定答案。
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/perfect-squares/solution/wan-quan-ping-fang-shu-by-leetcode-solut-t99c/
1 public int numSqu(int n){ 2 if (isPerSqu(n)){ 3 return 1; 4 } 5 if (checkAns4(n)){ 6 return 4; 7 } 8 for (int i =1; i * i < n;i++){ 9 int j = n - i*i ; 10 if(isPerSqu(j)){ 11 return 2; 12 } 13 } 14 return 3; 15 } 16 17 public boolean isPerSqu(int x) { 18 int y = (int) Math.sqrt(x); 19 return y*y == x; 20 } 21 22 public boolean checkAns4(int x){ 23 while (x % 4 ==0) { 24 x /= 4; 25 } 26 return x % 8 == 7; 27 }
标签:平方,return,int,完全,答案,public 来源: https://www.cnblogs.com/ytfso321/p/14876729.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。