假设我被赋予了一个任意数组,只有正值,例如A[5] = {2,3,4,2}
。我希望检查一下int x
,让我们说x=2
,看看A[2]
是否可以是数组中其他元素的总和。在这种情况下它可以,因此我们可以打印TRUE
因为A[0]
和A[3]
加起来A[2]
。对于具有例如100个元素或更多元素的更大数组,什么是找出A[x]
是否可以由同一数组中的其他元素求和的好方法?
答案 0 :(得分:0)
这有点暴力O(n * log(n))。
#include <iostream>
#include <algorithm>
#include <vector>
bool check_helper( std::vector< int > & data, std::vector< int >::iterator position, int value )
{
#if 0
std::cout << "check2helper( data, " << *position << ", " << value << ")\n";
#endif
if( *position == value )
return true;
else if( position == data.begin() )
return false;
else return check_helper( data, position - 1, value - *position ) || check_helper( data, position - 1, value );
}
bool check( const std::vector< int > & data, size_t element_index )
{
std::vector< int > data_copy( data );
int value = data_copy[element_index];
data_copy.erase( data_copy.begin() + element_index );
std::sort( data_copy.begin(), data_copy.end() );
std::vector< int >::iterator iter( std::lower_bound( data_copy.begin(), data_copy.end(), value ) );
#if 0
std::cout << " Checking " << value << " in ";
for( std::vector< int >::iterator i( data_copy.begin() ); i <= iter; ++i )
std::cout << *i << " , ";
std::cout << std::endl;
#endif
return check_helper( data_copy, iter, value );
}
int main( int argc, char ** argv )
{
std::vector< int > ints{ 1, 2, 4, 23, 97, 146, 11, 17, 301, 24, 12, 2 };
std::cout << "Testing ints = ";
for( auto v : ints )
std::cout << v << ", ";
std::cout << std::endl;
for( size_t i = 0; i < ints.size(); ++i )
{
std::cout << "ints[" << i << "] == " << ints[i] << " ---> " << ( check( ints, i ) ? "TRUE" : "FALSE" ) << std::endl;
}
return 0;
}
结果:
Testing ints = 1, 2, 4, 23, 97, 146, 11, 17, 301, 24, 12, 2,
ints[0] == 1 ---> FALSE
ints[1] == 2 ---> TRUE
ints[2] == 4 ---> TRUE
ints[3] == 23 ---> TRUE
ints[4] == 97 ---> FALSE
ints[5] == 146 ---> TRUE
ints[6] == 11 ---> FALSE
ints[7] == 17 ---> TRUE
ints[8] == 301 ---> TRUE
ints[9] == 24 ---> TRUE
ints[10] == 12 ---> TRUE
ints[11] == 2 ---> TRUE