How to get all possible combination of 2xn matrix [closed]

This problem is already asked,
you can use backtracking to solve it
here’s the code,

#include<conio.h>
#include<stdio.h>
int a[2][100],c,sum,num;
int ch;
int check(int x,int y)
{
    int i=1;
    if(x==1&&a[x][y]>a[0][y])
    i=0;
    if(y>0&&a[x][y]>a[x][y-1])
    i=0;
    return i;
}
void print()
{
    int i,j;
    printf("\n");
    for(i=0;i<2;i++)
    {
        for(j=0;j<num;j++)
        printf("%4d",a[i][j]);
        printf("\n");
    }
}
void fun(int lim,int x,int y)
{
    int i;
    if(y<num)
    for(i=lim;i>0;i--)
    {
        a[x][y]=i;  
        if(check(x,y))
        {
            sum+=a[x][y];
            if(sum==num)
            {
                print();
                sum-=a[x][y];
                a[x][y]=0;
                c++;
            }
            else
            {
                fun(num-sum,(x+1)%2,y+(x+1)/2);
                a[(x+1)%2][y+(x+1)/2]=0;
                fun(num-sum,(x+2)%2,y+(x+2)/2);
                a[(x+2)%2][y+(x+2)/2]=0;
            }
            sum-=a[x][y];
        }
    }
}

int main()
{   
    scanf("%d",&num);//num=6
    fun(num,0,0);
    printf("%d",c);
    return 0;
}

Leave a Comment