这是解决背包问题的正确方法吗?

时间:2019-02-12 19:18:05

标签: algorithm knapsack-problem

我正在尝试练习面试问题,并遇到了背包问题。这是解决问题的正确方法吗?

我尚未进行递归方法。复杂度为O(n2)吗?

private void kpsolve()
{           
        int[] items = new int[] { 1, 2, 3, 4 , 5, 6};
        int[] weights = new int[] { 1, 2, 3, 8 ,7 ,4};
        int[] profits = new int[] { 20, 5 ,10, 40, 15,25 };

        int capacity = 10;

        //number of items in a set that can yield max profits
        Dictionary<List<int>, int> weightmap = new Dictionary<List<int>, int>();
        for(int i=0;i< weights.Length;i++)
        {
            List<int> currList = new List<int>();
            int runprofit = 0;
            int runweight = 0;
            var w = weights[i];
            var p = profits[i];
            int cw = w;

            if (w > capacity)
                continue;

            currList.Add(i);
            runprofit = p;
            runweight = w;

            for (int j = 0; j < weights.Length; j++)
            {
                if (j == i)
                    continue;

                var iw = weights[j];
                var ip = profits[j];

                if ((runweight + iw) <= capacity)
                {
                    currList.Add(j);
                    runprofit += ip;
                    runweight += iw;
                }

            }

            weightmap.Add(currList, runprofit);
        }
        var lvalues = weightmap.Max(w => w.Value);

    }

0 个答案:

没有答案