Notice
Recent Posts
Recent Comments
Link
«   2025/12   »
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
Archives
Today
Total
관리 메뉴

hwooo

LeetCode (C/C++) 279. Perfect Squares 본문

Study/Algorithm

LeetCode (C/C++) 279. Perfect Squares

hwooo 2024. 6. 6. 17:02

https://leetcode.com/problems/perfect-squares/description/


풀이

dp를 이용, 제곱수일 때의 개수를 1로 초기화한다.

현재 숫자에 도달하기 위해서는 이전의 제곱수 값들을 더해야 하므로, 현재 숫자보다 작은 제곱수에 저장된 값들로 최소 수의 합을 구한다


코드

class Solution {
public:
    int numSquares(int n) {
        int dp[10001];
        fill(dp, dp + 10001, 10001);

        // 제곱수는 1로 초기화
        int num = 1;
        while (num * num <= n) {
            dp[num * num] = 1;
            num++;
        }
        
        for (int i = 1; i <= n; i++) {
            if (dp[i] != 10001) continue;
            
            // 현재 숫자보다 적은 제곱수에 저장된 값 사용
            for (int j = 1; j * j <= i / 2; j++) {
                dp[i] = min(dp[i], dp[i - j * j] + dp[j * j]);
            }
        }
        return dp[n];
    }
};