简体   繁体   中英

dictionary stays the same when returning from recursion

I have this piece of code that uses recursion to calculate the sum of something on all numbers up to limit.

static long gen(int limit, List<int> primes,int num,int idx,myDict dict,long sum)
    {

        for (int i = idx; i < primes.Count; i++)
        {
            if (num * primes[i] > limit || num * primes[i] < 0)
            {
                return 0;
            }
            dict.update(primes[i]);
            Console.WriteLine("{0}-->{1}", num * primes[i], dict.maxv);
            gen(limit, primes, num * primes[i], i, dict, sum + dict.maxv);
        }
        return sum;
    }

myDict is basically a dictionary that saves it's max value and the key to that value.

My problem is that dict is not changing when returning from the recursion. I mean that if for example I debug the function and in the call stack there are a few calls to this function and I try to examine the values of the variables there. num holds the value it should according to when it was called but dict always holds the "newest" value.

lets take an example that in the call stack the value for num is currently 8 and dict currently holds the values: 2:(3,4) the dict that we should have is this. but if I examine the previous calls in the call stack I find that in all of them dict has the same value and not the value that it had when the function was could from there.

I think that maybe there is some conceptual idea that I'm not understanding correctly.

If myDict is essentially a Dictionary , it is always passed by reference to the gen method. This means that there is only one instance of myDict and in every iteration of your recursive method dict refers to this one and only instance. Simply returning from gen will pop the reference to your myDict from the stack, but this will not change its contents. If you want to return dict to its previous state, you will have to implement the backtracking yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM