已知一個數組,保存了n個(n<=15)火柴棍,問能否使用這n個火柴棍擺成1個正方形?
ios
代碼實現:數組
#include<iostream> #include<vector> #include<algorithm> using namespace std; bool solution(int i, vector<int> &nums, int target, int bucket[]) { if(i >= nums.size()) return (bucket[0] == target && bucket[1] == target && bucket[2] == target && bucket[3] == target); for(int j = 0; j < 4; j++) { if(bucket[j] + nums[i] > target) continue; bucket[j] += nums[i]; if(solution(i+1, nums, target, bucket)) return true; bucket[j] -= nums[i]; } return false; } int main() { vector<int> a; int t,n; cin>>t; while(t--) { cin>>n; a.push_back(n); } if(a.size() < 4) { cout<<"false"<<endl; return 0; } int sum = 0; for(int i = 0; i < a.size(); i++) sum += a[i]; if(sum % 4) { cout<<"false"<<endl; return 0; } int bucket[4] = {0}; sort(a.rbegin(), a.rend()); cout<<solution(0, a, sum/4, bucket)<<endl; return 0; }