Python 代码到 Java 代码的转换

Python code to Java code conversion

我在 python 中写了一些代码,效果非常好,我试图在 Java 中实现它,但遇到了一些小问题。这是一个简单的 21 题,使用回溯法从用户那里获取字符串输入,例如 " 1 9 10"

这里是 python 代码:

def twentyone(nums, stack = [], answer = set()):
    for index, num in enumerate(nums):
        new_stack = stack + [num]
        total = sum(new_stack)
        if total == 21:
            answer.add(tuple(new_stack))
        elif total < 21:
            twentyone(nums[index + 1:], new_stack, answer)
    return answer

user_input = input()
list_format = [int(x) for x in user_input.split()]
answer = twentyone(list_format)

if len(answer) == 0:
    print("No combination of numbers add to 21")
for solution in answer:
    print("The values ", end = "")
    for number in solution:
            print("{} ".format(number), end = "")
    print("add up to 21")

这是我的 java 代码(到目前为止)

public class TwentyOne {

   public static void main(String args[]){
      Scanner userInput = new Scanner(System.in);
      String stringInput = userInput.nextLine();

      ArrayList<Integer> allNum = new ArrayList<>();
      for (String num : stringInput.split(" ")){
         allNum.add(Integer.parseInt(num));
      }

      HashSet<ArrayList<Integer>> answer = twentyOne(allNum);

      for (ArrayList<Integer> solution : answer){
         System.out.print("The values ");
         for (Integer num : solution){
            System.out.print(num + " ");
         }
         System.out.println("Add up to 21");
      }
   }



   private static HashSet twentyOne(ArrayList<Integer> user_input){

      return new HashSet<ArrayList<Integer>>();
   }
}

基本上,我无法在参数中没有变量初始化的情况下编写 java 递归问题。

def twentyone(nums, stack = [], answer = set()):

所以我的问题是,如何在我将进行递归调用的方法中处理 java 没有变量初始化的回溯?

您将编写一个传递默认参数的包装方法。例如:

twentyone(List<Integer> nums) {
    twentyoneRecursive(nums, new ArrayDeque<>(), new HashSet<>());
}

twentyoneRecursive(List<Integer> nums, Deque<Integer> stack, Set<List<Integer>> answer) {
    ...
    twentyoneRecursive(...);
}