其实就是全排列(数字可重复,参见leetcode46,47)+一点限制条件(完全平方数)
#include <iostream>
#include<stdlib.h>
#include<string>
#include<vector>
#include<set>
#include<math.h>
#include<map>
#include<unordered_map>
#include<algorithm>
#include<functional>
#include<queue>
using namespace std;
map<int, int>mymap;//key为元素,value为该元素出现的次数
vector<vector<int>>v;//记录与第i个数字的和为完全平方数的数字的下标
map<int, vector<int>>maps;
vector<int> a = { 1,8,17 };
vector<int>uniques;//记录非重复的数字
vector<int>ans;
void print() {
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
cout << endl;
}
//
void getPrefect() {
//必须先排序
sort(a.begin(), a.end());
for (int i = 0; i < a.size(); i++) {
//获得唯一数字和重复次数
if (uniques.size() == 0 || a[i-1] != a[i]) {
uniques.push_back(a[i]);
mymap[a[i]] = 1;
}
else
mymap[a[i]]++;
}
}
//判断是否为完全平方数
bool isPerfect(int num) {
if (int(pow(sqrt(num), 2)) == num)
return true;
return false;
}
void process(int current) {
if (current == a.size()) {
print();
return;
}
for (int i = 0; i < uniques.size(); i++)
if (current == 0 || (isPerfect(ans[current - 1] + uniques[i])&&mymap[uniques[i]]>0)) {
ans.push_back(uniques[i]);
mymap[uniques[i]]--;
process(current + 1);
mymap[uniques[i]]++;
ans.pop_back();
}
}
int main() {
getPrefect();
process(0);
system("pause");
return 0;
}