# 135. 数字组合

vector<vector<int>> combinationSum(vector<int> &candidates, int target)
{
set<vector<int>> ret;
sort(candidates.begin(), candidates.end());
multimap<int,vector<int>> mVec;
for (int i = 0; i < candidates.size(); i++)
{
int num = candidates[i];
if (num > target)
{
continue;
}
if (num == target)
{
vector<int> tmpVec;
tmpVec.push_back(num);
ret.insert(tmpVec);
continue;
}
vector<int> tmpVec;
tmpVec.push_back(num);
mVec.insert(pair<int,vector<int>>(num,tmpVec));
}

while (!mVec.empty())
{
multimap<int, vector<int>> mTmpVec;
for (auto it : mVec)
{
int sum = it.first;
vector<int> tmpVec = it.second;
int top = tmpVec.back();
for (int i = 0; i < candidates.size(); i++)
{
if (top > candidates[i])
{
continue;
}
if (sum + candidates[i] > target)
{
continue;
}
if (sum + candidates[i] == target)
{
tmpVec.push_back(candidates[i]);
ret.insert(tmpVec);
}
tmpVec.push_back(candidates[i]);
mTmpVec.insert(pair<int, vector<int>>(sum + candidates[i], tmpVec));
tmpVec = it.second;
}
}
mVec = mTmpVec;
}

vector<vector<int>> ret2;

for (auto it : ret)
{
ret2.push_back(it);
}

return ret2;
}

void test()
{
vector<int> candidates = { 2, 3, 6, 7 };
int target = 7;

vector<vector<int>> ret = combinationSum(candidates,target);
}

int main()
{
test();
getchar();
return 0;
}

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

yinhua405

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
10-11 29

01-31 557
11-09 83
02-24 138
07-19 438
11-07 347
10-16 329
05-10 163
09-13 1315