码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 39 Combination Sum

时间:2017-10-07 17:37:11      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:class   find   result   有用   深搜   pre   code   c++   pat   

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

 

For example, given candidate set [2, 3, 6, 7] and target 7
A solution set is: 

[
  [7],
  [2, 2, 3]
]
深搜DFS,我有想法但是没有用。。。。。唉唉唉,

#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <bits/stdc++.h>

using namespace std;

class solution
{
public:
void BFS(vector<int>& candidates, int target,int tmp_sum,int tmp_pos,vector<int>& path,vector<vector<int> >& result)
{

if (tmp_sum == target)
{
result.push_back(path);
return;
}
if (tmp_sum > target)
{
return;
}
for (int index = tmp_pos; index<candidates.size(); index++)
{
path.push_back(candidates[index]);
BFS(candidates,target,candidates[index] + tmp_sum,index,path,result);
path.pop_back();
}
}
vector<vector<int> > combinationSum(vector<int>& candidates, int target)
{
vector<vector<int> > result;
vector<int>path;
sort(candidates.begin(),candidates.end());
BFS(candidates,target,0,0,path,result);
return result;
}
};


bool campare(vector < vector<int> >ans,vector < vector<int> > result)
{
if (ans.size() != result.size() )
return false;

for (int i=0; i<ans.size(); i++)
{
if (ans[i].size() != result[i].size())
return false;
for (int j=0; j<ans[i].size(); j++)
{

if (ans[i][j] != result[i][j])
{
return false;
}
}
}
return true;
}

TEST_CASE("leetcode 39 ")
{
int arr[5] = {2,3,6,7};
int ans1[5] = {2,2,3};
int ans2[3] = {7};
vector<int> candidates(arr,arr+4);
vector < vector<int> > correct;
vector<int> v1(ans1,ans1+3),v2(ans2,ans2+1);
correct.push_back(v1);
correct.push_back(v2);
solution test;
vector < vector<int> > result = test.combinationSum(candidates, 7);

REQUIRE(campare(correct,result ) == true);

}

 用 catch 第一个单元测试的代码,感觉并没有很方便耶。。。。

leetcode 39 Combination Sum

标签:class   find   result   有用   深搜   pre   code   c++   pat   

原文地址:http://www.cnblogs.com/sxy-798013203/p/7634605.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!