1 / 2
May 2020
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int isPossible(char str[2][100001],char ch,int pos,int N)
{
    if(pos==0){
        if(str[0][pos]==ch)
        return 0;
    }
    else{
        if(str[0][pos]==ch||str[1][pos-1]==ch)
        return 0;
    }
    return 1;
}
int printPattern(int N,char str[2][100001],char posColor[4],int count[4],int pos)//O(8*n)
{
    ///printing colors
    if(pos==2*N){
    str[1][pos]='\0';
    printf("%s",str[1]);
    return 1;
    }
        for(int i=0;i<4;i++){
            if(count[i]==0)
            continue;
            
            if(isPossible(str,posColor[i],pos,N)){
                str[1][pos]=posColor[i];
                count[i]--;
                int res=printPattern(N,str,posColor,count,pos+1);
                    if(res==1)
                       return 1;
                    else{
                       str[1][pos]='X';
                       count[i]++;
                    }
            }
        }
    return 0;
}
int main()
{
    int N;
    scanf("%d",&N);
    char str[2][100001];
    scanf(" %s",str[0]);
    char posColor[4]={'A','B','C','D'};
    int count[4];
    for(int i=0;i<4;i++)
    count[i]=N;
    for(int i=0;i<2*N;i++){ ///O(2N)
        if(str[0][i]=='A')
        count[0]--;
        else if(str[0][i]=='B')
        count[1]--;
        else if(str[0][i]=='C')
        count[2]--;
        else
        count[3]--;
    }
    printPattern(N,str,posColor,count,0);//O(8N)
    return 0;
}
  • created

    May '20
  • last reply

    May '20
  • 1

    reply

  • 537

    views

  • 2

    users

  • 1

    link

You’re using recursion without the memoisation - add some memoisation to printPattern and see what a difference it makes.

ABCD2