回溯算法(Java)

本文介绍了一种使用Java编程语言实现的算法,通过回溯法寻找给定数组中所有加起来等于指定和的整数组合。该方法通过递归遍历数组,避免重复,最终输出所有符合条件的组合。
摘要由CSDN通过智能技术生成

在给定的数中,找到所以加起来的和恰好等于指定的数的数集。

import java.util.ArrayList;
import java.util.List;

public class a {
    public static void main(String[] args) {
        int[] nums = {2, 4, 5,6, 3, 7}; // 给定的一堆数
        int targetSum = 9; // 指定的和

        List<List<Integer>> result = new ArrayList<>(); // 用于存储结果的列表
        backtrack(nums, targetSum, 0, new ArrayList<>(), result); // 调用回溯方法查找满足条件的组合

        // 输出结果
        for (List<Integer> combination : result) {
            System.out.println(combination);
        }
    }

    private static void backtrack(int[] nums, int target, int start, List<Integer> path, List<List<Integer>> result) {
        // 如果目标和为0,表示找到了满足条件的组合,将其添加到结果列表中
        if (target == 0) {
            result.add(new ArrayList<>(path));
            return;
        }

        // 从起始位置开始遍历数组
        for (int i = start; i < nums.length; i++) {
            // 如果当前数字小于等于目标和,则选择当前数字进行组合
            if (nums[i] <= target) {
                // 选择当前数字
                path.add(nums[i]);
                // 继续向下搜索,但是起始位置从i+1开始,避免重复使用同一个数字
                backtrack(nums, target - nums[i], i + 1, path, result);
                // 回溯,撤销选择,继续尝试其他可能的组合
                path.remove(path.size() - 1);
              
                for (int num : path) {
                    System.out.println(num);
                }
              
            }
        }
    }
}

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值