[Reflection] 343 Integer Break

Claim

  • Given a positive number n, you can divide it into the sum of multiple numbers and find the division method that maximizes the product of these numbers (at least divided into two numbers)

Examples

  • n = 2, return 1 (2 = 1 + 1)
  • n = 10, return 36 (10 = 3 + 3 + 4)

achieve

  • Backtracking traversal (n ^ 2, timeout)

1  class Solution {
 2  private :
 3      int max3 ( int a, int b, int c) {
 4          return max (a, max (b, c));
 5      }
 6      
7      // divide n (at least two parts) The maximum product that can be obtained is 
8      int breakInteger ( int n) {
 9          
10          if (n == 1 )
 11              return  1 ;
 12              
13          int res = -1 ;
 14          for ( int i = 1 ; i <= n-1 ; i ++ )
15             // i + (n-i)
16             res = max3( res, i * (n-i) , i * breakInteger(n-i) );
17         
18         return res;
19     }
20 
21 public:
22     int integerBreak(int n) {
23         return breakInteger(n);
24     }
25 };
View Code
  • Memory search
1  class Solution {
 2  private :
 3      vector < int > memo;
 4      
5      int max3 ( int a, int b, int c) {
 6          return max (a, max (b, c));
 7      }
 8      
9      // will n The maximum product that can be obtained by dividing (at least two parts) 
10      int breakInteger ( int n) {
 11          
12          if (n == 1 )
 13              return  1 ;
 14          
15          if( memo[n] != -1)
16             return memo[n];
17                 
18         int res = -1;
19         for( int i = 1 ; i <= n-1 ; i ++ )
20             // i + (n-i)
21             res = max3( res, i * (n-i) , i * breakInteger(n-i) );
22         memo[n] = res;
23         return res;
24     }
25 
26 public:
27     int integerBreak(int n) {
28         memo = vector<int>(n+1,-1);
29         return breakInteger(n);
30     }
31 };
View Code
  • Dynamic programming
1  class Solution {
 2  private :
 3      int max3 ( int a, int b, int c) {
 4          return max (a, max (b, c));
 5      }
 6  
7  public :
 8      int integerBreak ( int n) {
 9          assert (n> = 2 );
 10          
11          // memo [i] means the maximum product obtained by dividing at least the number i (at least two parts) 
12          vector < int > memo (n + 1 , -1 );
 13         
14         memo[1] = 1;
15         for( int i = 2 ; i <= n ; i ++ )
16             // 求解memo[j] 
17             for( int j = 1 ; j <= i-1 ; j ++ )
18                 // j + (i-j)
19                 memo[i] = max3(j*(i-j) , j*memo[i-j] , memo[i] );
20         
21         return memo[n];
22     }
23 };
View Code

Related

  • 279 Perfect Squares
  • 91 Decode Ways
  • 62 Unique Paths
  • 63 Unique Paths II

Guess you like

Origin www.cnblogs.com/cxc1357/p/12717372.html