Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

c# - Method returns null values despite having a value before return

I took a liberty of copying this code and adjusted it to C#

private static List<List<int>> Subsets(List<int> A)
        {
            List<int> subset = new List<int>();
            List<List<int>> res = new List<List<int>>();

            int index = 0;
            SubsetsUtil(A, ref res, ref subset, index);
            //here res becomes "empty"
            return res;
        }

        private static void SubsetsUtil(List<int> A, ref List<List<int>> res, ref List<int> subset, int index)
        {
            if (subset.Count > 0)
            {
                res.Add(subset);
            }

            for (int i = index; i < A.Count(); i++)
            {
                // include the A[i] in subset. 
                subset.Add(A[i]);

                // move onto the next element. 
                SubsetsUtil(A, ref res, ref subset, i + 1);

                // exclude the A[i] from subset and triggers 
                // backtracking. 
                subset.RemoveAt(subset.Count - 1);
            }
            return;
        }

On paper it looks amazing, but for some reason Subsets method returns list that contains proper count of subsets, but they are all empty. When I placed some traps inside SubsetsUtil method results are actually saving properly to res variable, but after SubsetsUtil method is finished inside Subsets, res no longer contains it.

I have absolutely no idea how to fix it, it looks like a glitch in environment, but I'm pretty sure I'm just missing some little tiny detail.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...