• LeetCode-39-组合总数


    LeetCode-39-组合总数

    题目

    给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

    candidates 中的数字可以无限制重复被选取。

    说明:

    所有数字(包括 target)都是正整数。
    解集不能包含重复的组合。
    示例 1:

    输入:candidates = [2,3,6,7], target = 7,
    所求解集为:
    [
    [7],
    [2,2,3]
    ]
    示例 2:

    输入:candidates = [2,3,5], target = 8,
    所求解集为:
    [
    [2,2,2,2],
    [2,3,3],
    [3,5]
    ]

    提示:

    1 <= candidates.length <= 30
    1 <= candidates[i] <= 200
    candidate 中的每个元素都是独一无二的。
    1 <= target <= 500

    思路

    一开始以为用动态规划,后来发现需要求的是所有,那么就属于搜索问题了;

    我的思路是用dfs来做,做一个路径来记录选取的数字,每选择一个数字,就把target减去此数字;

    当target等于0时,则记录此path,小于0的时候直接返回,大于0的时候继续;

    如果遍历候选数组进行选取会出现场重复,所以用一个pos记录当前选取数字的位置;

    每次只能从当前数字出发,往后选取即可:

    代码

    class Solution {
    public:
        int candidatesLength;
        vector<vector<int>> ans;
        void dfs(vector<int>& path, int target, vector<int>& candidates, int pos) {
            if (target == 0) {
                ans.push_back(path);
                return;
            }
            if (target < 0) return;
            for (int i=pos; i<candidatesLength; i++) {
                int x = candidates[i];
                path.push_back(x);
                dfs(path, target-x, candidates, i);
                path.pop_back();
            }
        } 
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            candidatesLength = candidates.size();
            if (candidatesLength <= 0) return ans;
            vector<int> path;
            dfs(path, target, candidates, 0);
            return ans;
        }
    };
    
  • 相关阅读:
    Trie
    [转]Tarjan应用:求割点/桥/缩点/强连通分量/双连通分量/LCA(最近公共祖先)
    [Bzoj2242]常见数值算法
    JavaScript百炼成仙(记录笔记)
    tcpreplay重放报文,tcpdump能抓到包,应用程序收不到包
    用jquery tools来实现选项卡
    ExtNet第二篇
    线性表最简单的表示
    c语言中线性表基本操作方法
    ExtNet第一篇
  • 原文地址:https://www.cnblogs.com/sakurapiggy/p/13449476.html
Copyright © 2020-2023  润新知