You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于动态天数变量的排列矩阵实现:循环与参数动态化需求

动态生成指定天数的排列矩阵实现方案

要解决动态天数下的排列矩阵生成问题,不用硬编码多层for循环,直接用回溯法就能实现完全适配days变量的逻辑,代码如下:

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

public class PermutationGenerator {
    public static ArrayList<ArrayList<Integer>> computePermutations(int stops, int days) {
        int maxPerDay = stops - (days - 1);
        ArrayList<ArrayList<Integer>> permutationMatrix = new ArrayList<>();
        // 启动回溯,初始状态:已选列表为空,当前处理第0天,剩余站点数为stops
        backtrack(new ArrayList<>(), 0, stops, maxPerDay, days, permutationMatrix);
        return permutationMatrix;
    }

    private static void backtrack(List<Integer> current, int dayIndex, int remainingStops, int maxPerDay, int totalDays, ArrayList<ArrayList<Integer>> result) {
        // 终止条件:处理完所有天数
        if (dayIndex == totalDays) {
            // 剩余站点数刚好为0,说明当前组合符合条件
            if (remainingStops == 0) {
                result.add(new ArrayList<>(current));
            }
            return;
        }

        // 遍历当前天可能的站点数:从1开始,不超过maxPerDay,同时不能超过剩余站点数(避免后续天数没站点分配)
        for (int i = 1; i <= Math.min(maxPerDay, remainingStops); i++) {
            current.add(i);
            // 递归处理下一天,剩余站点数减去当前选择的数值
            backtrack(current, dayIndex + 1, remainingStops - i, maxPerDay, totalDays, result);
            // 回溯:移除当前选择的数值,尝试下一个可能
            current.remove(current.size() - 1);
        }
    }
}

关键逻辑说明

  • 回溯核心:通过递归代替多层for循环,每一层递归对应一天的站点数选择,自动适配days的数值,不用手动修改循环结构。
  • 边界控制:
    • 每天的站点数从1开始(保证每天至少有1个站点)
    • 上限取maxPerDay和remainingStops的最小值,避免出现后续天数无站点可分配的情况
  • 结果收集:当处理完所有天数且剩余站点数为0时,将当前组合存入结果集合,自动生成对应长度的列表,不用手动调整Arrays.asList的参数。

内容的提问来源于stack exchange,提问作者Hakano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 15:27:21