forked from forging2012/JavaArithmetic
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode279_no.java
More file actions
103 lines (77 loc) · 2.99 KB
/
LeetCode279_no.java
File metadata and controls
103 lines (77 loc) · 2.99 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package LeetCode;
import javafx.util.Pair;
import java.util.LinkedList;
public class LeetCode279_no {
// 279. Perfect Squares
// https://leetcode.com/problems/perfect-squares/description/
// 该方法会导致 Time Limit Exceeded 或者 Memory Limit Exceeded
//
// 时间复杂度: O(2^n)
// 空间复杂度: O(2^n)
public int numSquares(int n) {
LinkedList<Pair<Integer, Integer>> queue = new LinkedList<Pair<Integer, Integer>>();
queue.addLast(new Pair<Integer, Integer>(n, 0));
while (!queue.isEmpty()) {
Pair<Integer, Integer> front = queue.removeFirst();
int num = front.getKey();
int step = front.getValue();
if (num == 0)
return step;
for (int i = 1; num - i * i >= 0; i++)
queue.addLast(new Pair(num - i * i, step + 1));
}
throw new IllegalStateException("No Solution.");
}
// 使用visited数组,记录每一个入队元素
// 时间复杂度: O(n)
// 空间复杂度: O(n)
public int numSquares2(int n) {
LinkedList<Pair<Integer, Integer>> queue = new LinkedList<Pair<Integer, Integer>>();
queue.addLast(new Pair<Integer, Integer>(n, 0));
boolean[] visited = new boolean[n + 1];
visited[n] = true;
while (!queue.isEmpty()) {
Pair<Integer, Integer> front = queue.removeFirst();
int num = front.getKey();
int step = front.getValue();
if (num == 0)
return step;
for (int i = 1; num - i * i >= 0; i++)
if (!visited[num - i * i]) {
queue.addLast(new Pair(num - i * i, step + 1));
visited[num - i * i] = true;
}
}
throw new IllegalStateException("No Solution.");
}
// 时间复杂度: O(n)
// 空间复杂度: O(n)
public int numSquares3(int n) {
if (n == 0)
return 0;
LinkedList<Pair<Integer, Integer>> queue = new LinkedList<Pair<Integer, Integer>>();
queue.addLast(new Pair<Integer, Integer>(n, 0));
boolean[] visited = new boolean[n + 1];
visited[n] = true;
while (!queue.isEmpty()) {
Pair<Integer, Integer> front = queue.removeFirst();
int num = front.getKey();
int step = front.getValue();
if (num == 0)
return step;
for (int i = 1; num - i * i >= 0; i++) {
int a = num - i * i;
if (!visited[a]) {
if (a == 0) return step + 1;
queue.addLast(new Pair(num - i * i, step + 1));
visited[num - i * i] = true;
}
}
}
throw new IllegalStateException("No Solution.");
}
public static void main(String[] args) {
System.out.println((new LeetCode279_no()).numSquares(12));
System.out.println((new LeetCode279_no()).numSquares(13));
}
}