Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

จำนวนวิธีรวมได้ N ด้วยสมาชิกในอาเรย์ (允许重复) ใน C++


ในโจทย์นี้ เราได้รับอาเรย์ของจำนวนเต็มและจำนวน N งานของเราคือนับจำนวนวิธีทั้งหมดที่ N สามารถสร้างได้โดยการบวกสมาชิกของอาเรย์ ทุกการจัดหมู่และการซ้ำได้รับอนุญาต

ตัวอย่าง

อินพุต

arr = {1, 3, 5} N = 6

เอาต์พุต

8

คำอธิบาย

วิธีต่างๆ คือ:

5+1, 1+5, 3+3, 3+1+1+1, 1+3+1+1, 1+1+3+1, 1+1+1+3, 1+1+1+1+1+1

เพื่อแก้ปัญหานี้ เราต้องใช้วิธีการที่แตกต่างกัน เนื่องจากทุกประเภทของการจัดหมู่จะถูกนับแยกกัน ดังนั้น ถ้าจำนวนหนึ่งเป็นผลรวมของ 4 สมาชิกของอาเรย์ จะมี 4 วิธีที่แตกต่างกัน (ตามตัวอย่าง) สำหรับการแก้ปัญหาแบบนี้ เราต้องใช้วิธี Dynamic Programming และโปรแกรมด้านล่างจะแสดงการนำไปใช้

ตัวอย่าง

#include <iostream>
#include <cstring>
using namespace std;

int arraySumWays(int array[], int size, int N) {
    int count[N + 1];
    memset(count, 0, sizeof(count));
    count[0] = 1;
    for (int i = 1; i <= N; i++)
        for (int j = 0; j < size; j++)
            if (i >= array[j])
                count[i] += count[i - array[j]];
    return count[N];
}

int main() {
    int array[] = {1, 5, 6};
    int size = sizeof(array) / sizeof(array[0]);
    int N = 7;
    cout << "Total number of ways in which " << N << " can be generated using sum of elements of array is "
         << arraySumWays(array, size, N);
    return 0;
}

ผลลัพธ์

Total number of ways in which 7 can be generated using sum of elements of array is 6