算法:Ruby解决方案超时,但Java不是

时间:2017-07-22 22:16:09

标签: java ruby algorithm time-complexity

对于以下算法问题,我有以下两种解决方案:

Suppose you have N integers from 1 to N. We define a beautiful
arrangement as an array that is constructed by these N numbers
successfully if one of the following is true for the ith position (1 <=
i <= N) in this array:

The number at the ith position is divisible by i. 
i is divisible by the number at the ith position. Now given N, how many beautiful
arrangements can you construct? (N will be <= 15)

以下是Java中提供的解决方案:

public class Solution {
    int count = 0;
    public int countArrangement(int N) {
        boolean[] visited = new boolean[N + 1];
        calculate(N, 1, visited);
        return count;
    }
    public void calculate(int N, int pos, boolean[] visited) {
        if (pos > N)
            count++;
        for (int i = 1; i <= N; i++) {
            if (!visited[i] && (pos % i == 0 || i % pos == 0)) {
                visited[i] = true;
                calculate(N, pos + 1, visited);
                visited[i] = false;
            }
        }
    }
}

这是我的Ruby解决方案:

def count_arrangement(n)
    visited = Array.new(n + 1) # zero index left blank
    count_arrangements(n, visited, 1)[:arrangements]
end

def count_arrangements(n, visited, i)
    return { arrangements: 1, recursed: true } if i == n + 1 # this is end of one arrangement
    max_arrangements = 0
    recursed = false

    1.upto(n) do |num|
        next if visited[num]
        if num % i == 0 || i % num == 0
            recursed = true
            this_visited = visited.dup
            this_visited[num] = true
            arrangements_obj = count_arrangements(n, this_visited, i + 1) # recursive depth only goes up to O(N)
            if arrangements_obj[:recursed]
              max_arrangements += arrangements_obj[:arrangements]
            end
        end
    end
    recursed ? { arrangements: max_arrangements, recursed: true } : { arrangements: -1, recursed: false }
end

似乎算法的复杂性是相同的(AFAIK),但我的Ruby解决方案超出了Java的解决方案。有谁知道这是为什么?

0 个答案:

没有答案