Why can't backtracking generate all possible combinations?
I have a 2D array of a shape {{"x"},{"a","b","c"},{"1","2","3"}}
.
I want to generate all of the following combinations:
xa1
xa2
xa3
xb1
xb2
xb3
xc1
xc2
xc3
I wrote the following recursive code to create combinations:
String dim[][] ={{"x"},{"a","b","c"},{"1","2","3"}};
void fun(int i,int j,String []metric)
{
if(i>=dim.length)
{
for(int k=0;k<i;k++)
System.out.print(metric[k]);
System.out.println();
return;
}
if(j>=dim[i].length)
return;
metric[i] = dim[i][j];
fun(i+1,j,metric);
fun(i,j+1,metric);
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
String metric[] = new String[20];
Ideone b = new Ideone();
b.fun(0,0,metric);
}
And I get the following incomplete output:
xa1
xa2
xa3
xb2
xb3
xc3
I cannot generate the whole combination as mentioned and I cannot figure out in which case I cannot see an error in my logic.
+3
source to share
1 answer