C语言递归方法求解背包问题
生活随笔
收集整理的這篇文章主要介紹了
C语言递归方法求解背包问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C語言遞歸方法求解背包問題
- C語言遞歸方法求解背包問題,編譯環境vs2019
- 上問題:
- 上代碼:
C語言遞歸方法求解背包問題,編譯環境vs2019
上問題:
十、背包問題的求解
假設有一個能裝入總體積為T的背包和n件體積分別為w1 , w2 , … , wn 的物品,能否從n件物品中挑選若干件恰好裝滿背包,即使w1 +w2 + … + wn=T,要求找出所有滿足上述條件的解。例如:當T=10,各件物品的體積{1,8,4,3,5,2}時,可找到下列4組解:
(1,4,3,2)
(1,4,5)
(8,2)
(3,5,2)。
上代碼:
#include<stdio.h> int answer[100] = { 0 };//保存結果 int p = 0;//answer的指針 void bag(int *nums, int locate, int total, int len, int big) {for (int i = locate; i < len; i++) {total += answer[p++] = nums[i];//total取和,answer保存當前的數if (total < big) {//比背包小的時候進入遞歸bag(nums, i + 1, total, len, big);total -= answer[--p];//遞歸結束減去當前數,準備進入下一次循環}else if (total > big)//比背包大total -= answer[--p];else if (total == big) {//和背包相等打印結果for (int j = 0; j < p; j++)printf("%d ", answer[j]);printf("\n");total -= answer[--p];}} } void main() {int nums[] = { 1,8,4,3,5,2 }, big = 10, total = 0, len = sizeof(nums)/sizeof(int), locate = 0;bag(nums, locate, total, len, big); }總結
以上是生活随笔為你收集整理的C语言递归方法求解背包问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring mvc学习(53):回顾和
- 下一篇: 查找算法分析