我喜欢用
Python处理列表的方式.它做任何递归解决方案看起来容易和干净.例如,在Python中获取元素的所有排列的典型问题如下所示:
def permutation_recursion(numbers,sol): if not numbers: print "this is a permutation",sol for i in range(len(numbers)): permutation_recursion(numbers[:i] + numbers[i+1:],sol + [numbers[i]]) def get_permutations(numbers): permutation_recursion(numbers,list()) if __name__ == "__main__": get_permutations([1,2,3])
我喜欢通过这样的方式简单地获取修改列表的新实例的方式
数字[:i]数字[i 1:]或sol [数字[i]]
如果我尝试在Java中编写完全相同的代码,它看起来像:
import java.util.ArrayList; import java.util.Arrays; class rec { static void permutation_recursion(ArrayList<Integer> numbers,ArrayList<Integer> sol) { if (numbers.size() == 0) System.out.println("permutation="+Arrays.toString(sol.toArray())); for(int i=0;i<numbers.size();i++) { int n = numbers.get(i); ArrayList<Integer> remaining = new ArrayList<Integer>(numbers); remaining.remove(i); ArrayList<Integer> sol_rec = new ArrayList<Integer>(sol); sol_rec.add(n); permutation_recursion(remaining,sol_rec); } } static void get_permutation(ArrayList<Integer> numbers) { permutation_recursion(numbers,new ArrayList<Integer>()); } public static void main(String args[]) { Integer[] numbers = {1,3}; get_permutation(new ArrayList<Integer>(Arrays.asList(numbers))); } }
要创建相同的递归,我需要做:
ArrayList<Integer> remaining = new ArrayList<Integer>(numbers); remaining.remove(i); ArrayList<Integer> sol_rec = new ArrayList<Integer>(sol); sol_rec.add(n);
解决方法
没有.
但这就是为什么Martin Odersky创造了Scala.他甚至说他对Scala的目标之一就是它是Java世界的Python. Scala编译为Java字节码,并且可以轻松地与Java编译类进行交互.
如果这不是一个选项,你可以看看Commons Collection Library.