leetcode 279. Perfect Squares

不念不忘少年蓝@ 2022-08-20 13:14 133阅读 0赞

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. // ConsoleApplication1.cpp : Defines the entry point for the console application.
  2. //
  3. #include "stdafx.h"
  4. #include<vector>
  5. #include<iostream>
  6. using namespace std;
  7. class Solution {
  8. private:
  9. int minnum;
  10. vector<int>minpath;
  11. public:
  12. void do_once(int squarenum,int& remain,vector<int>&path)
  13. {
  14. if(path.size()>=minnum-1)
  15. return;
  16. for(int i=squarenum;i>=1;i--)
  17. {
  18. vector<int>pathcopy=path;
  19. pathcopy.push_back(i);
  20. int rem=remain-i*i;
  21. if(rem==0)
  22. {
  23. if(pathcopy.size()<minnum)
  24. {
  25. minnum=pathcopy.size();
  26. minpath=pathcopy;
  27. }
  28. }
  29. else if(rem>0)
  30. {
  31. if(pathcopy.size()+1<minnum)
  32. {
  33. int startnum=sqrt(remain-i*i);
  34. if(startnum>i)
  35. startnum=i;
  36. do_once(startnum,rem,pathcopy);
  37. }
  38. }
  39. }
  40. }
  41. int numSquares(int n) {
  42. int outsquare=sqrt(n);
  43. minnum=100000;
  44. while(outsquare!=0)
  45. {
  46. if(n/(outsquare*outsquare)>=minnum)
  47. return minnum;
  48. int remain=n;
  49. vector<int>path;
  50. do_once(outsquare,remain,path);
  51. outsquare--;
  52. }
  53. }
  54. };
  55. int _tmain(int argc, _TCHAR* argv[])
  56. {
  57. Solution sl;
  58. cout<<sl.numSquares(7168);
  59. system("pause");
  60. return 0;
  61. }

超时

稍作修改

  1. class Solution {
  2. private:
  3. int minnum;
  4. vector<int>minpath;
  5. public:
  6. void do_once(int squarenum,int& remain,vector<int>&path)
  7. {
  8. if(path.size()>=minnum-1)
  9. return;
  10. for(int i=squarenum;i>=1;i--)
  11. {
  12. vector<int>pathcopy=path;
  13. pathcopy.push_back(i);
  14. int rem=remain-i*i;
  15. if(rem==0)
  16. {
  17. if(pathcopy.size()<minnum)
  18. {
  19. minnum=pathcopy.size();
  20. minpath=pathcopy;
  21. }
  22. }
  23. else if(rem>0)
  24. {
  25. if(pathcopy.size()+1<minnum)
  26. {
  27. int startnum=sqrt(remain-i*i);
  28. if(startnum>i)
  29. startnum=i;
  30. do_once(startnum,rem,pathcopy);
  31. }
  32. }
  33. }
  34. }
  35. int numSquares(int n) {
  36. int outsquare=sqrt(n);
  37. minnum=100000;
  38. while(outsquare!=0)
  39. {
  40. if(n/(outsquare*outsquare)>=minnum)
  41. return minnum;
  42. int insquare=sqrt(n-outsquare*outsquare);
  43. if(insquare>outsquare)
  44. insquare=outsquare;
  45. int remain=n-outsquare*outsquare;
  46. if(remain==0)
  47. return 1;
  48. vector<int>path;
  49. path.push_back(outsquare);
  50. do_once(insquare,remain,path);
  51. outsquare--;
  52. }
  53. return minnum;
  54. }
  55. };

accepted

发表评论

表情:
评论列表 (有 0 条评论,133人围观)

还没有评论,来说两句吧...

相关阅读