1.递归
int name(int n) {
if(满足边界条件) return ...;
if(满足边界条件) return ...;
...
else {
sbproblems...
...
return name(...) + ...
}
}
2.二分
2.1 左边界
int left_bound(int[] nums, int target) {
if (nums.length == 0) return -1;
int left = 0;
int right = nums.length;
while (left < right) {
int mid = (left + right) / 2;
if (nums[mid] == target) {
right = mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid;
}
}
return left;
}
2.2右边界
int right_bound(int[] nums, int target) {
if (nums.length == 0) return -1;
int left = 0, right = nums.length;
while (left < right) {
int mid = (left + right) / 2;
if (nums[mid] == target) {
left = mid + 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid;
}
}
return left - 1;
}
3.搜索
3.1dfs
Void DFS(deep,...){
if(找到解 || 走不下去了){
......
return;
}
for(扩展方式){
if(扩展方式所能达到的状态合法){
修改操作;
标记;
DFS(deep+1,...);
}
}
}
3.2bfs
void BFS(){
初始化队列Q;
起点S入队;
标记S已经访问;
while(Q非空){
取Q的队首元素U;
U出队列;
if(u==目标状态){
返回结果;
}
for(所有与U相邻的元素){
if(相邻的元素合法 && 未访问){
入队;
标记访问;
}
}
}
}