• 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 第一个单元测试的代码,感觉并没有很方便耶。。。。

  • 相关阅读:
    循环神经网络
    第四次作业:卷积神经网络 part 3
    《Strip Pooling: Rethinking Spatial Pooling for Scene Parsing》——笔记
    《Selective Kernel Networks》——笔记
    《Non-local Neural Networks 》——笔记
    HybridSN中添加SE模块
    第三次作业:卷积神经网络 part 2
    第一次作业:深度学习及pytorch基础
    需要背的板子
    Codeforces 1474F. 1 2 3 4 ... 题解
  • 原文地址:https://www.cnblogs.com/sxy-798013203/p/7634605.html
Copyright © 2020-2023  润新知