[刷题] LeetCode 279 Perfect Squares

Claim

  • Given a positive integer n, find the least perfect square, and to make their n

Examples

  • n = 12
  • 12 = 4 + 4 + 4
  • Output: 3

boundary

  • Is it possible no solution?

Thinking

  • Greedy: 12 = 1 + 1 + 9 + 1, the optimal solution can not be obtained
  • FIG: from 0 to n, each number denotes a node, if the two numbers differ from x to y a perfect square, one side of the connection
  • It is converted to the shortest path problem not entitled to figures from 0 to n

  

achieve

 1 class Solution {
 2 public:
 3     int numSquares(int n) {
 4         
 5         assert( n > 0 );
 6         
 7         queue< pair<int,int> > q;
 8         q.push( make_pair( n , 0 ) );
 9         
10         while( !q.empty() ){
11             int num = q.front().first;
12             int step = q.front().second;
13             q.pop();
14             
15             if( num == 0 )
16                 return step;
17                 
18             for( int i = 1 ; num - i*i >=0 ; i ++ )
19                 q.push( make_pair( num - i * i , step + 1 ) );
20         }
21         
22         throw invalid_argument("No Solution");
23     }
24 };
View Code
  • Some nodes are repeatedly pushed into the queue, there is a performance problem when n is large enough
  • Unlike the tree, each node has a variety of FIG path to
  • With a secondary vector records node is pushed through the queue
  • Optimization end condition
 1 class Solution {
 2 public:
 3     int numSquares(int n) {
 4         
 5         assert( n > 0 );
 6         
 7         queue< pair<int,int> > q;
 8         q.push( make_pair( n , 0 ) );
 9         
10         vector<bool> visited(n+1, false);
11         visited[n] = true;
12         
13         while( !q.empty() ){
14             int num = q.front().first;
15             int step = q.front().second;
16             q.pop();
17             
18             for( int i = 1 ; ; i ++ ){
19                 int a = num - i*i;
20                 if( a < 0 )
21                     break;
22                 if( a == 0)
23                     return step + 1;
24                 if( ! visited[a] ){
25                 q.push( make_pair( a , step + 1 ) );
26                 visited[a] = true;
27             }
28         }
29     }
30     throw invalid_argument("No Solution");
31     }
32 };
View Code

Related

  • 127 Word Ladder
  • 126 Word Ladder II

 

Guess you like

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