องค์ประกอบที่ไม่ต่อเนื่องกันหารด้วย n ลงตัวไม่ทำงาน

วิธีที่มีประสิทธิภาพในการนับจำนวนลำดับย่อยที่ไม่ต่อเนื่องกันของอาร์เรย์ที่กำหนดซึ่งหารด้วย n คืออะไร A = {1,2,3,2} n = 6 เอาต์พุต 3 เพราะ 12, 12, 132 หารด้วย 6 ลงตัว

โซลูชันของฉันที่ใช้การเขียนโปรแกรมแบบไดนามิกให้ผลลัพธ์ที่ผิด มันมักจะให้มากกว่าผลลัพธ์ที่แท้จริงหนึ่งอย่างเสมอ

#include <stdio.h>

#define MAXLEN 100
#define MAXN 100
int len = 1,ar[] = {1, 6, 2},dp[MAXLEN][MAXN],n=6;

int fun(int idx,int m)
{
    if (idx >= (sizeof(ar)/sizeof(ar[0])))
        return m == 0;
    if(dp[idx][m]!=-1)
        return dp[idx][m];
    int ans=fun(idx+1,m);                // skip this element in current sub-sequence
    ans+=fun(idx+1,(m*10+ar[idx])%n);    // Include this element. Find the new modulo by 'n' and pass it recursively
    return dp[idx][m]=ans;
}
int main()
{
    memset(dp, -1, sizeof(dp));
    printf("%d\n",fun(0, 0));            // initially we begin by considering array of length 1 i.e. upto index 0
    return 0;
}

ใครสามารถชี้ให้เห็นข้อผิดพลาด?


person noman pouigt    schedule 29.09.2015    source แหล่งที่มา


คำตอบ (1)


ปัญหาคือลำดับ "ว่าง" ถือเป็นวิธีแก้ปัญหา (m == 0 เมื่อคุณเริ่มการโทรและไม่เพิ่มตัวเลขใดๆ จะทำให้คุณมี m == 0 ในตอนท้าย)

นั่นก็ถูกต้องแล้ว แต่คำตอบของ {1, 2, 3, 2} ก็คือ 4 หรือคุณต้องลบออกโดยให้ตอบกลับเป็น fun(0, 0)-1

person 6502    schedule 29.09.2015