> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/dfs-and-bfs/generic-dfs/279.-perfect-squares.md).

# 279. Perfect Squares

T: O(sqrt(n)\*n).  , because we have n memo, search on this memo,

and for loop is sqrt(n)

````java
```java
class Solution {
    public int numSquares(int n) {
        Integer[] memo = new Integer[n+1];
        List<Integer> candidate = new ArrayList<>();
        for (int i = 1; i*i <= n; i++) { // calculate candidates(perfect squares) first
            candidate.add(i*i);
            memo[i*i] = 1; // complete by itself
        }
        memo[0] = 0;
        dfs(n, candidate, memo);
        return memo[n];
    }
    private int dfs(int n, List<Integer> candidate, Integer[] memo) {
        if (n == 0 || memo[n] != null) {
            return memo[n];
        }
        int result = Integer.MAX_VALUE;
        for (int i = candidate.size()-1; i >= 0; i--) { // like sort, use larger one to substract , more efficient
            int c = candidate.get(i);
            if (n - c >= 0) {
                result = Math.min(result, dfs(n - c, candidate, memo)+1);
            }
        }
        return memo[n] = result;
    }
}

/*

base case: target == 0

count = dfs(target - i*i) + 1

    12
    /\|\\
   1 4 9 
   /. 
  11.    8.        3
  /     7 4 x 
1 4 9

10 7 2
you can see 7 has duplicate cases

  this can do the memo

  T 

why can memo? there are many duplicate case
  dfs(12) = dfs(8) + 1

*/
```
````


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/dfs-and-bfs/generic-dfs/279.-perfect-squares.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
