背包問題的java實現

來源:互聯網
上載者:User

背包問題的描述:

 

有一系列的物件,他佔用部分空間size,擁有價值value,給定你固定的空間cap,怎麼樣找到最高價值?

 

 

public class KnapsackProblem {
 static class Item {
  int size;
  int val;

  public Item(int s, int v) {
   this.size = s;
   this.val = v;
  }
 }

 static Item item[] = new Item[5];
 static int N = 5;
 static {
  item[0] = new Item(3, 4);
  item[1] = new Item(4, 5);
  item[2] = new Item(7, 10);
  item[3] = new Item(8, 11);
  item[4] = new Item(9, 13);
 }

 static int knap(int capacity) {
  int i, space, max, t;
  for (i = 0, max = 0; i < N; i++) {
   if ((space = capacity - item[i].size) >= 0) {
    if ((t = knap(space) + item[i].val) > max) {
     max = t;
    }
   }
  }
  return max;
 }

 public static void main(String[] args) {
  System.out.println(knap(17));
 }

}

該版本代碼為未最佳化的版本,後期的版本等我閱讀完奉上。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.