我是 Ruby 编程的新手,我正在尝试编写一个 Ruby 代码,它将按特定顺序获取数字列表,并返回排列列表列表中的所有可能排列。我不久前用 Java 成功地编写了这个程序并且它工作了,当我试图在 Ruby 中实现相同的逻辑时,我只是得到空列表的列表而不是排列。通过初始调试,我可以观察到每个排列都通过回溯方法成功地构建在 temp_list 列表中,但不知何故 res 没有正确保留推送的排列。我认为我在 Ruby 中的编码风格有问题。有人可以指出可能是什么问题。我附上了我的 Ruby 和 Java 代码。
我的 Ruby 代码在这里:
# @param [Object] nums : List of numbers Example: [1, 2, 3]
# @return [Object] res : List of all permutation lists Example [[1, 2, 3], [1, 3, 2]....]
def permute(nums)
res = []
temp_list = []
backtrack(res, temp_list, nums)
res
end
# @param [Object] res : List of all permutation lists Example [[1, 2, 3], [1, 3, 2]....]
# @param [Object] temp_list : List of permutation which is being built
# @param [Object] nums : Original nums list given to the permute method
def backtrack(res, temp_list, nums)
if temp_list.size == nums.size
res << temp_list
else
nums.each do |n|
next if temp_list.include? n
temp_list << n
backtrack(res, temp_list, nums)
temp_list.pop
end
end
end
我的 JAVA 代码在这里:
import java.util.ArrayList;
import java.util.List;
/**
* Created by Srikiran Sistla on 4/3/2017.
*/
public class Q46 {
public List<List<Integer>> permute(int[] num) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tempList = new ArrayList<>();
backtrack(res, tempList, num);
return res;
}
private void backtrack(List<List<Integer>> res, List<Integer> tempList, int[] num) {
if (tempList.size() == num.length) res.add(new ArrayList<>(tempList));
else {
for (int n : num){
if (tempList.contains(n)) continue;
tempList.add(n);
backtrack(res, tempList, num);
tempList.remove(tempList.size()-1);
}
}
}
}
最佳答案
这很奇怪,但我已经解开了你的代码:)
你所需要的只是克隆你的临时列表,然后将它附加到 res:
res << temp_list.dup
仅供引用,您可以通过调用标准 Array#permutation 来节省一些时间:
[1,2,3].permutation.to_a # => [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
关于java - 使用回溯的排列程序在 Ruby 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46305883/