首页 > 试题广场 >

实现一个函数,返回整数数组中所有唯一组合。假设数组中元素无重

[单选题]
实现一个函数,返回整数数组中所有唯一组合。假设数组中元素无重复。
import java.util.*;

public class UniqueCombinations {

    public static List<List<Integer>> combine(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(result, new ArrayList<>(), nums, 0);
        return result;
    }

    private static void backtrack(List<List<Integer>> result, List<Integer> tempList,
                                  int[] nums, int start) {
        result.add(new ArrayList<>(tempList));
        
        for (int i = start; i < nums.length; i++) {
            ____ // 填空
            backtrack(result, tempList, nums, i + 1);
            tempList.remove(tempList.size() - 1);
        }
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        List<List<Integer>> combinations = combine(nums);
        
        for (List<Integer> combination : combinations) {
            System.out.println(combination);
        }
    }
}

填空内容是:
  • tempList.add(nums[i])
  • nums[i] > 0
  • Collections.addAll(tempList, nums[i])
  • tempList.contains(nums[i])
纯蒙,对于这么一行首先可以排除所有的判断语句bd,然后看下一行可知要传入参数tempList,所以选A
发表于 2025-10-15 10:21:59 回复(0)
要解决这个问题,我们需要实现一个函数,返回整数数组中所有可能的唯一组合(即所有子集)。
     ### 分析代码逻辑 给定的代码使用回溯法生成所有组合: 1. `combine` 方法初始化结果列表,并调用 `backtrack` 方法开始回溯。 2. `backtrack` 方法是核心: - 首先将当前临时列表(`tempList`)加入结果集(记录当前组合)。 - 然后通过循环遍历数组元素,从 `start` 索引开始(避免重复组合)。 - 循环中需要先将当前元素加入临时列表,再递归生成后续组合,最后移除元素(回溯)。
     ### 填空分析 循环中需要执行的操作是将当前元素 `nums[i]` 加入临时列表 `tempList`,才能继续递归生成包含该元素的组合。观察选项: - A. `tempList.add(nums[i])`:正确,将当前元素加入临时列表,符合回溯法的逻辑。 - B. `nums[i] > 0`:无关的条件判断,与组合生成无关。 - C. `Collections.addAll(tempList, nums[i])`:语法错误,`Collections.addAll` 需传入集合或数组,不能直接传入单个整数。 - D. `tempList.contains(nums[i])`:检查元素是否存在,返回布尔值,无法完成添加元素的操作。 答案:A
发表于 2025-08-12 17:01:58 回复(2)
回溯算法,每次需要挑一个元素进入List。
发表于 2025-08-15 21:27:43 回复(0)