problem : "To rank in every possible elements of the set {1,2, ..., n} so that the numbers i, i + 1, ..., i + k to be one after the other and in this order(i=1,i+k≤n)."
my question is how do i find k numbers and in that order i tried backtracking method but unfortunately it doesn't want to output numbers, probably must be like (k+1)k!=(k+1)!..(k+2)k!=(k+2)! and so on i guess
#include <iostream>
usingnamespace std;
int n,v[20];
int valid(int k);
int solution(int k);
void output(int k);
void BK(int k);
int main()
{cout<<"n= ";
cin>>n;
BK(1);
return 0;
}
void BK(int k) //method backtracking
{int i;
for (i=1;i+k<=n;i++)
{v[k]=i;
if (valid(k))
{if (solution(k))
output(k);
else
BK(k+1);
}
}
}
int valid(int k) //check if a number is still in set of elements(vector)
{int i;
for (i=1;i<=k-1;i++)
if (v[i]==v[k])
return 0;
return 1;
}
int solution(int k) //finding solution
{if (k==n)
return 1;
return 0;
}
void output(int k) //output result
{int i;
for (i=1;i<=k;i++)
cout<<v[i]<<" ";
cout<<endl;
}