java - 使用回溯的排列程序在 Ruby 中不起作用

标签 java ruby algorithm

我是 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/

相关文章:

java - 更新另一个 swing gui 类中的 jTextField

ruby - 使用正则表达式拒绝数组中的项目的语法

database - 维护 "ordering string"以排序数据库元素的算法

algorithm - 有没有一种根据 Jaccard 相似度对图进行聚类的有效方法?

java - 如何为具有整数键的json对象创建pojo类?

java - 无法删除嵌入式数据库的 Derby 系统目录

java - Maven CAS 和 Restfullapi

ruby - 使用 rspec 在 ruby​​ gem 测试中加载 fixture

ruby - 使用 REST API 下载现有的 Paypal 付款

算法-涉及if语句时如何计算时间复杂度