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
My solution:
I had to refer to blogs to solve it..
(code reference blog: https://somjang.tistory.com/entry/BaeKJoon-1699%EB%B2%88-%EC%A0%9C%EA%B3%B1%EC%88%98%EC%9D%98-%ED%95%A9-Python)
(idea reference blog: https://it-and-life.tistory.com/76)
inputNum = int(input()) nc = [0] * (inputNum+1) for i in range(1, inputNum+1): nc[i] = i for j in range(1, i): if (j * j) > i: break nc[i] = min(nc[i], nc[i - j * j] + 1) print(nc[inputNum])