算法--路径总和

描述

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例

在这里插入图片描述

分析

从根节点开始,使用递归,判断左节点或者右节点到叶子节点是否存在sum-root.val即可。

实现

class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }
        // 到达叶子节点时,递归终止,判断 sum 是否符合条件。
        if (root.left == null && root.right == null) {
            return root.val == sum;
        }
        // 递归地判断root节点的左孩子和右孩子。
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}

### 蚁群算法实现商队旅行最短路径计算优化 #### 算法概述 蚁群算法是一种基于群体智能的元启发式优化算法,最初由 Marco Dorigo 提出并应用于解决旅行商问题 (TSP)[^1]。该算法模仿自然界中蚂蚁觅食的行为模式,利用正反馈机制逐步构建解决方案。对于商队旅行问题(可视为 TSP 的变种),蚁群算法能够有效探索可能的路径集合,并通过迭代更新信息素浓度来逼近全局最优解。 #### 数学模型 在蚁群算法中,每只虚拟蚂蚁根据概率选择下一条边行走,其转移概率定义如下: \[ P_{ij}^{k}(t)= \frac{\left[\tau_{ij}(t)\right]^{\alpha}\cdot\left[\eta_{ij}(t)\right]^{\beta}}{\sum_{l \in N_i^k(t)}\left[\tau_{il}(t)\right]^{\alpha}\cdot\left[\eta_{il}(t)\right]^{\beta}} \] 其中: - \( P_{ij}^{k}(t) \): 第 k 只蚂蚁从节 i 到 j 的转移概率; - \( \tau_{ij}(t) \): 边 (i, j) 上的信息素强度; - \( \eta_{ij}(t) \): 启发因子,通常表示为距离倒数 \( 1/d(i,j) \); - \( \alpha,\beta \): 控制信息素和启发因子相对重要性的参数[^1]; 每次迭代结束后,需按照以下公式更新信息素浓度: \[ \tau_{ij}(t+1)=(1-\rho)\cdot\tau_{ij}(t)+\Delta\tau_{ij} \] 其中: - \( \rho \): 信息素蒸发系数; - \( \Delta\tau_{ij}=\sum_k Q/L_k\) : 所有经过边 (i, j) 的蚂蚁留下的信息素增量总和,\( L_k \) 表示第 k 条路径长度,Q 是常量。 #### Python 实现示例 以下是使用蚁群算法求解商队旅行最短路径的一个简单 Python 示例: ```python import numpy as np import random class AntColonyOptimization: def __init__(self, distances, n_ants=10, alpha=1, beta=5, evaporation_rate=0.5, q_value=100): self.distances = distances self.n_cities = len(distances) self.pheromone = np.ones((self.n_cities, self.n_cities)) self.alpha = alpha self.beta = beta self.evaporation_rate = evaporation_rate self.q_value = q_value self.n_ants = n_ants def run(self, iterations): shortest_path = None all_time_shortest_distance = float('inf') for _ in range(iterations): paths = [] for ant in range(self.n_ants): path = self.generate_ant_path() paths.append(path) self.update_pheromones(paths) current_best_path = min(paths, key=lambda x: self.calculate_total_distance(x)) current_best_distance = self.calculate_total_distance(current_best_path) if current_best_distance < all_time_shortest_distance: all_time_shortest_distance = current_best_distance shortest_path = current_best_path return shortest_path, all_time_shortest_distance def generate_ant_path(self): visited = [False]*self.n_cities start_city = random.randint(0, self.n_cities - 1) visited[start_city] = True path = [start_city] while False in visited: next_city = self.select_next_city(path[-1], visited) path.append(next_city) visited[next_city] = True return path def select_next_city(self, current_city, visited): unvisited_cities = [city for city in range(self.n_cities) if not visited[city]] probabilities = [(self.pheromone[current_city][next_city]**self.alpha * ((1 / self.distances[current_city][next_city])**self.beta)) for next_city in unvisited_cities] total_probabilities = sum(probabilities) normalized_probabilities = [p/total_probabilities for p in probabilities] selected_city_index = list(np.random.multinomial(1, normalized_probabilities)).index(1) return unvisited_cities[selected_city_index] def update_pheromones(self, paths): self.pheromone *= (1-self.evaporation_rate) for path in paths: distance = self.calculate_total_distance(path) pheromone_to_add = self.q_value / distance for i in range(len(path)-1): self.pheromone[path[i]][path[i+1]] += pheromone_to_add def calculate_total_distance(self, path): total_distance = 0 for i in range(len(path)-1): total_distance += self.distances[path[i]][path[i+1]] return total_distance distances = [ [0, 29, 20, 21], [29, 0, 15, 17], [20, 15, 0, 18], [21, 17, 18, 0] ] aco = AntColonyOptimization(distances) shortest_path, shortest_distance = aco.run(100) print(f'Shortest Path: {shortest_path}') print(f'Shortest Distance: {shortest_distance}') ``` 此代码实现了基本的蚁群算法框架,适用于小型数据集上的测试案例[^1]。 #### 参数调优建议 为了提高蚁群算法性能,在实际应用中应仔细调整以下几个关键参数: - **α 和 β**: 这两个参数控制信息素与启发函数之间的权衡关系。较大的 α 值倾向于依赖历史信息,而较高的 β 值则强调当前状态的影响。 - **ρ**: 决定信息素挥发速度,过低可能导致早熟收敛,过高会减缓学习进程。 - **Q**: 影响单次迭代中新增信息素总量,一般设为固定值即可满足需求[^1]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值