โจทย์
Each person must ride exactly once. Any group can share a ride if the sum of its weights is no greater than capacity. People may be regrouped freely; their input order does not matter. Minimize the number of rides.
Implement elevator_rides(weights, capacity).
Input
weights: The weight of each person.
capacity: The maximum combined weight in a ride.
Output
Return the minimum number of rides.
เงื่อนไข
1 ≤ people ≤ 20. 1 ≤ capacity ≤ 1,000,000,000. Every weight is between 1 and capacity.
ตัวอย่าง
อินพุต:
weights = [3, 4, 5]
capacity = 7
ผลลัพธ์ที่คาดหวัง:
expected = 2
อินพุต:
std::vector<long long> weights = {3, 4, 5};
long long capacity = 7;
ผลลัพธ์ที่คาดหวัง:
long long expected = 2;
อินพุต:
long[] weights = new long[] {3, 4, 5};
long capacity = 7;
ผลลัพธ์ที่คาดหวัง:
long expected = 2;
คำอธิบาย
Send 3 + 4 together and 5 separately. Total weight 12 cannot fit in one ride of capacity 7.
อินพุต:
weights = [2, 2, 2]
capacity = 6
ผลลัพธ์ที่คาดหวัง:
expected = 1
อินพุต:
std::vector<long long> weights = {2, 2, 2};
long long capacity = 6;
ผลลัพธ์ที่คาดหวัง:
long long expected = 1;
อินพุต:
long[] weights = new long[] {2, 2, 2};
long capacity = 6;
ผลลัพธ์ที่คาดหวัง:
long expected = 1;
คำอธิบาย
All three people fit together because 2 + 2 + 2 = 6.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
Since the number of people is small, consider subsets rather than individual rides.
คำใบ้ 2
Track both how many rides are used and how full the current last ride is for each subset.
คำใบ้ 3
When two states use the same number of rides, prefer the one with smaller current load.
ความซับซ้อนที่คาดหวัง
O(2^n * n) time, O(2^n) extra space
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน