分治
分治、递归、重复性
分治寻找复杂问题的重复性步骤,化成子问题;
50. Pow(x, n)
class Solution {
public:
double myPow(double x, int n) {
long long N = n;
if(N<0){
x = 1/x;
N = -N;
}
return Pow(x,N);
}
double Pow(double x, long long n){
if(n==0) return 1.0;
if(n==1) return x;
double t = Pow(x,n/2); // 【处理子问题,得到子结果】
if(n%2!=0){
return t * t * x;
}else{
return t * t;
}
}
};
169. 多数元素
class Solution:
def majorityElement(self, nums: List[int]) -> int:
if not nums:
return None
if len(nums) == 1:
return nums[0]
left = self.majorityElement(nums[:len(nums)//2])
right = self.majorityElement(nums[len(nums)//2:])
if left == right:
return left
if nums.count(left) > nums.count(right):
return left
else:
return right
分治代码模板
def divide_conquer(problem, param1, param2, ...):
# recursion terminator
if problem is None:
print_result
return
# prepare data
data = prepare_data(problem)
subproblems = split_problem(problem, data)
# conquer subproblems
subresult1 = self.divide_conquer(subproblems[0], p1, ...)
subresult2 = self.divide_conquer(subproblems[1], p1, ...)
subresult3 = self.divide_conquer(subproblems[2], p1, ...)
...
# process and generate the final result
result = process_result(subresult1, subresult2, subresult3, ...)
# revert the current level states
int divide_conquer(Problem *problem, int params){
// recursion terminator
if(problem == nullptr){
process_result
return return_result;
}
// process current problem
subproblems = split_problem(problem, data);
subresult1 = divide_conquer(subproblems[0], p1);
subresult2 = divide_conquer(subproblems[1], p1);
subresult3 = divide_conquer(subproblems[2], p1);
...
// merge
result = process_result(subresult1, subresult2, subresult3);
// revert the current level status
return 0;
}
private static int divide_conquer(Problem problem, ) {
if (problem == NULL) {
int res = process_last_result();
return res;
}
subProblems = split_problem(problem)
res0 = divide_conquer(subProblems[0])
res1 = divide_conquer(subProblems[1])
result = process_result(res0, res1);
return result;
}
Javascript
const divide_conquer = (problem, params) => {
// recursion terminator
if (problem == null) {
process_result
return
}
// process current problem
subproblems = split_problem(problem, data)
subresult1 = divide_conquer(subproblem[0], p1)
subresult2 = divide_conquer(subproblem[1], p1)
subresult3 = divide_conquer(subproblem[2], p1)
...
// merge
result = process_result(subresult1, subresult2, subresult3)
// revert the current level status
}