c++ - combinations of k-tuple from n elements set by recursive -
#include <vector> #include <iostream> using namespace std; void subsetnum(bool * select, int*a, int selectk, int k, int selectn, int n )// depthk { if(k>n) return; if(selectn==n) { if(selectk==k) { for(int i=0;i<n;i++) if(select[i]==true) cout<<a[i]; cout<<endl; } return; } select[selectk]=false; subsetnum(select,a,selectk,k,selectn+1,n); select[selectk]=true; subsetnum(select,a,selectk+1,k,selectn+1,n); } int main() { int k=3; int n=5; int a[]={1,5,8,10,13}; //while(cin>>k) { bool *select=new bool[n]; memset(select,0,sizeof(bool)*n); subsetnum(select,a,0,k,0,n); delete []select; } homecoming 0; }
this question, want k elements n elements set.
but prints out wrong answer? confused when design recursive algorithms...especially parameter of functions, if or not homecoming value, , on, seek forcely remember code in textbook.
your error here:
select[selectk]=false; ... select[selectk]=true; it should this:
select[selectn]=false; ... select[selectn]=true; i believe cause of error failure remember variables represent. variable selectn index of element beingness included or excluded. variable selectk number of elements included. not create sense utilize selectk index a.
c++ algorithm recursion
No comments:
Post a Comment