Monday, August 17, 2015

LeetCode [279] Perfect Squares


279. Perfect Squares
Medium

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

Example 1:

Input: n = 12
Output: 3 
Explanation: 12 = 4 + 4 + 4.

Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution{
public:
    //bt: TLE
    int numSquares(int n){
        int m = sqrt(n);
        vector<int> vec(m);
        for(int i=1; i<=m; ++i){
            vec[i-1] = i*i;
        }
        int min_sz = INT_MAX;
        bt(vec, n, min_sz, m, 0, 0, 0);
        return min_sz;
    }
    void bt(vector<int> vec, int target, int &min_sz, int sz, int pos, int cur_sz, int sum){
        if(sum==target){
            min_sz = min(min_sz, cur_sz);
        }else if(pos<sz && sum<target && cur_sz<min_sz){
            for(int i=pos; i<sz; ++i){
                if(sum+vec[i]>target) return;
                bt(vec, target, min_sz, sz, i, cur_sz+1, sum+vec[i]);
            }
        }
    }

    //dp: 428 ms
    int numSquares(int n){
        vector<int> dp(n+1); 
        for(int i=0; i<=n; ++i){
            dp[i] = i;
            if(i>3){
                int r = sqrt(i);
                for(int j = r; j>=1; --j){
                    dp[i] = min(dp[i], 1+dp[i-j*j]);
                }
            }
        }
        return dp[n];
    }
};

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
    public int numSquares(int n) {
        int[] dp = new int[n+1];
        for(int i=1; i<=n; ++i){
            dp[i] = Integer.MAX_VALUE;
            for(int j=1; j*j<=i; ++j){
                dp[i] = Math.min(dp[i], 1+dp[i-j*j]);
            }
        }
        return dp[n];
    }
}

No comments:

Post a Comment