Example of Big O of 2^n

后端 未结 7 569
情歌与酒
情歌与酒 2021-01-31 09:11

So I can picture what an algorithm is that has a complexity of n^c, just the number of nested for loops.

for (var i = 0; i < dataset.len; i++ {
    for (var         


        
7条回答
  •  执笔经年
    2021-01-31 09:44

    Think about e.g. iterating over all possible subsets of a set. This kind of algorithms is used for instance for a generalized knapsack problem.

    If you find it hard to understand how iterating over subsets translates to O(2^n), imagine a set of n switches, each of them corresponding to one element of a set. Now, each of the switches can be turned on or off. Think of "on" as being in the subset. Note, how many combinations are possible: 2^n.

    If you want to see an example in code, it's usually easier to think about recursion here, but I can't think od any other nice and understable example right now.

提交回复
热议问题