我在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回溯,我将进行递归调用?
答案 0 :(得分:0)
您将编写一个传递默认参数的包装器方法。 e.g:
twentyone(List<Integer> nums) {
twentyoneRecursive(nums, new ArrayDeque<>(), new HashSet<>());
}
twentyoneRecursive(List<Integer> nums, Deque<Integer> stack, Set<List<Integer>> answer) {
...
twentyoneRecursive(...);
}