[关闭]
@LIUHUAN 2020-01-12T10:24:15.000000Z 字数 2058 阅读 671

动态规划从递归到结束

algorithm


分解整数

方法一:递归

  1. int integerBreak(int n) {
  2. //base case :just return for base case
  3. if(n <= 0)
  4. return 0;
  5. if(n == 2 || n == 1)
  6. return 1;
  7. if(n == 3)
  8. return 2;
  9. return intbreak(n);
  10. }
  11. int intbreak(int n) {
  12. if(n<=4)// case #1:the adder of sum
  13. return n;
  14. int r = 1;
  15. for(int i = 1; i < n-1; i++){
  16. int x = intbreak(n-i) * i;
  17. r = max(r,x);
  18. }
  19. return r;
  20. }

方法二:转化为备忘录递归

  1. unordered_map<int,int> umap;
  2. int integerBreak(int n) {
  3. if(n <= 0)
  4. return 0;
  5. if(n == 2 || n == 1)
  6. return 1;
  7. if(n == 3)
  8. return 2;
  9. // base case for integer break as adder
  10. for(int i = 1; i<= 4;i++) {
  11. umap[i] = i;
  12. }
  13. return intbreak(n);
  14. }
  15. int intbreak(int n) {
  16. if(umap.find(n) != umap.end()) {
  17. return umap[n];
  18. }
  19. int r = 1;
  20. for(int i=1; i < n-1; i++){
  21. int x = intbreak(n-i) * i;
  22. r = max(r,x);
  23. }
  24. umap[n] = r;
  25. return r;
  26. }

方法三:转化为递推(迭代)

  1. int integerBreak(int n) {
  2. if(n <= 0)
  3. return 0;
  4. if(n == 2 || n == 1)
  5. return 1;
  6. if(n == 3)
  7. return 2;
  8. vector<int> dp(n+1,0);
  9. // base case for adder n < 4
  10. dp[1] = 1;
  11. dp[2] = 2;
  12. dp[3] = 3;
  13. int x;
  14. for(int i = 4; i <= n; i++ ) {
  15. for(int k = i-1; k >= 1; k-- ) {
  16. x = dp[k] * (i-k);
  17. dp[i] = max(x,dp[i]);
  18. }
  19. }
  20. return dp[n];
  21. }

方法四:数学规律

  1. public int integerBreak(int n) {
  2. if(n == 2) return 1;
  3. if(n == 3) return 2;
  4. int product = 1;
  5. while( n > 4){
  6. product *= 3;
  7. n -= 3;
  8. }
  9. product *= n;
  10. return product;
  11. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注