【问题标题】:What is the time complexity of this dfs algorithm这个dfs算法的时间复杂度是多少
【发布时间】:2020-04-25 19:03:15
【问题描述】:

问题陈述:给定一个非负整数数组,您最初位于数组的第一个索引处。 // 一个leetcode问题

我只是对计算它的复杂性感到困惑。 tike 复杂度是多少,您能否推荐任何教授计算 tie 复杂度的书籍或教程

   class Solution {
    public boolean canJump(int[] nums,int sum,boolean isreach[]) {
        if(sum == nums.length-1){
            return true;
        }
        if(sum >= nums.length){
            return false;
        }
        if(isreach[sum]) return true;
        int j = nums[sum];
        int k = 1;
        boolean check = false;
        while( k <= j && sum + k < nums.length ){       
           check = check || canJump(nums, sum+k,isreach);
           if(check) {isreach[sum] = check; return true;}
           k++;
        }
        return false;
    }
    public boolean canJump(int[] nums) {
        boolean isreach[] = new boolean[nums.length];
        return canJump(nums,0,isreach);
    }
 }

在我看来,是n^2

【问题讨论】:

  • @maytham-ɯɐɥʇʎɐɯ 假设数组是 [3,3,3,3],所以调用的总数将是 3+2+1+0 = 6 是 n*(n-1)/2 所以它的 n^2

标签: java algorithm data-structures


【解决方案1】:

首先,这不是广度优先搜索算法。我很确定您所指的问题是Jump Game problem from LeetCode,其最佳解决方案是使用动态编程,而不是广度优先搜索。

您在上面介绍的算法只是一种自上而下的动态规划算法,它将解决方案记忆到它找到的较小的子问题。该算法的运行时间是O(N)(其中N 是您想要达到的sum 值),因为您将访问最多N 不同的状态。

【讨论】:

  • 我已经知道最佳解决方案,它确实是您从第一个数组元素开始的 dfs,然后它会调用下一个可能,直到您到达终点然后回溯
猜你喜欢
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-03
  • 2016-10-30
相关资源
最近更新 更多