1,刚开始练习算法的时候别人给的建议是“按主题刷”,这样容易熟悉这些题目的解题套路。后面我在网上发现了 labuladong 大神的网站,他更是总结了绝大部分的主题的解题公式模板,更容易吸收掌握。 labuladong 的算法小抄 :: labuladong的算法小抄
2,一些常用的解题模板就是树递归,回溯(决策树),图,比如字典树,并查集等,用的时候可以直接把模板代码先写上,像一个工具库一样。
并查集:
class UF {
int count;
int[] parent;
public UF(int n) {
count = n;
parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
public boolean connected(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
return rootP == rootQ;
}
private int find(int x) {
if (x != parent[x]) {
parent[x] = find(parent[x]);
}
return parent[x];
}
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) {
return;
}
parent[p] = q;
count--;
}
public int connect() {
return count;
}
}
二分图中的DFS和BFS:
class Solution13{
boolean ok=true;
boolean[] color;
boolean[] visited;
public boolean isBipartite(int[][] graph){
int n= graph.length;
color=new boolean[n];
visited=new boolean[n];
for (int v = 0; v < n; v++) {
if (!visited[v]){
bfs(graph,v);
}
}
return ok;
}
private void bfs(int[][] graph, int start) {
LinkedList<Integer> q = new LinkedList<>();
visited[start]=true;
q.offer(start);
while (!q.isEmpty()&&ok){
int v = q.poll();
for (int w : graph[v]) {
if (!visited[w]){
color[w]=!color[v];
visited[w]=true;
q.offer(w);
}else{
if (color[w]==color[v]){
ok=false;
return;
}
}
}
}
}
}
class Solution12 {
private boolean ok = true;
private boolean[] color;
private boolean[] visited;
public boolean isBipartite(int[][] graph) {
int n = graph.length;
color = new boolean[n];
visited = new boolean[n];
for (int v = 0; v < n; v++) {
if (!visited[v]) {
dfs(graph, v);
}
}
return ok;
}
private void dfs(int[][] graph, int v) {
if (!ok) {
return;
}
visited[v] = true;
for (int w : graph[v]) {
if (!visited[w]) {
color[w] = !color[v];
dfs(graph, w);
} else {
if (color[w] == color[v]) {
ok = false;
return;
}
}
}
}
}
字典树:
class WordDictionary {
private Node root = null;
private int size = 0;
public WordDictionary() {
}
private static class Node {
boolean end = false;
Node[] children = new Node[26];
}
private Node getNode(Node node , String key){
Node p = root;
for (int i = 0; i < key.length(); i++) {
if (p == null){
return null;
}
char c = key.charAt(i);
p = p.children[c-'a'];
}
return p;
}
public boolean get(String key){
Node p = getNode(root,key);
if (p == null || p.end == false){
return false;
}
return p.end;
}
public void addWord(String word) {
root = addWord(root,word,0);
}
private Node addWord(Node node , String key, int i){
if (node == null){
node = new Node();
}
if (i == key.length()){
node.end = true;
return node;
}
char c= key.charAt(i);
node.children[c-'a'] = addWord(node.children[c-'a'],key,i+1);
return node;
}
}
未完待续。。。