回溯法简单实例

 例1、从N个自然数(1,2,…,n)中选出r个数的所有组合
#include < iostream.h >
int main()
{
 int r, n;
 cout << “input the N: “;
 cin >> n;
 cout << “input the r: “;
 cin >> r;
 int *a = new int[ n ];//initialize
 int i = 0;
 int left = n – 1;
 a[ 0 ] = 1;
 int sum = 0;//record the total possibility
 do
 {
  do
  {
   if( i == r – 1 )
   {
    for( int k = 0; k < r; k++ )
     cout << a[ k ] << ” “;
    cout << endl;
    a[ i ] ++;
    sum ++;
   }
   else
   {
    if( a[ i ] <= n – r + i + 1 )
    {
     a[ i + 1 ] = a[ i ] + 1;
     ++ i;
    }
    else
     a[ –i ] ++;
   }
  }while( a[ i ] <= n – r + i + 1 );
 
  a[ –i ] ++;
 }while( a[ 0 ] < n – r + 2 );
 cout << “total ” << sum << endl;
 return 0;
}

例2 数的划分(noip2001tg)
问题描述 整数n分成k份,且每份不能为空,任意两份不能相同(不考虑顺序)。

 #include < iostream.h >

int main()
{
 int m, n;
 cout << “input the sum: “;
 cin >> n;
 cout << “input the number of parts: “;
 cin >> m;

 int *a = new int[ m ];//initialize
 int i = 0;
 int left = n – 1;
 a[ 0 ] = 1;

 int sum = 0;//record the total possibility

 do
 {
  if( i == m – 1 )
  {
   for( int k = 0; k < m; k ++ )
    cout << a[ k ] << ” “;
   cout << endl;
   a[ –i ] ++;
   left -= 1;
  }
  else
  {
   if ( left >= a[ i ] )//search
   {
    if( ++ i == m – 1 )
     a[ i ] = left;
    else
    {
     a[ i ] = a[ i – 1 ];
     left -= a[ i ];
    }
   }
   else //to look back
   {
    a[ –i ]++;
    left += a[ i + 1 ] – 1;
   }

  }
 }while( a[ 0 ] <= n / 3);

 return 0;
}

 

    原文作者:回溯法
    原文地址: https://blog.csdn.net/leonard520/article/details/4829504
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞