leetcode 39 Combination Sum

Posted Militant_799

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 39 Combination Sum相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode题意分析&解答39. Combination Sum

Leetcode 39. Combination Sum

[leetcode-39-Combination Sum]

leetcode 39. Combination Sum

[array] leetcode - 39. Combination Sum - Medium

LeetCode39Combination Sum