算法通关村-----回溯模板如何解决排列组合问题

组合总和

问题描述

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 对于给定的输入,保证和为 target 的不同组合数少于 150 个。详见leetcode39

问题分析

我们可以从candidates[0]开始,不断选取candidates[0],直至target-candidates[0]<=0,如果等于0,则我们得到一个满足条件的组合,否则回退一步,去掉一个candidates[0],添加一个candidates[1],如此不断进行下去,满足局部枚举➕递归+放下前任,我门可以使用回溯模板来解决。

代码实现

java 复制代码
public List<List<Integer>> combinationSum(int[] candidates, int target) {
    List<Integer> numList = new ArrayList<>();
    List<List<Integer>> resultList = new ArrayList();
    combinationSum(candidates,target,0,numList,resultList);
    return resultList;
}

public void combinationSum(int[] candidates, int target,int index,List<Integer> numList,List<List<Integer>> resultList){
    if(target<0){
        return;
    }
    if(target==0){
        resultList.add(new ArrayList<>(numList));
        return;
    }
    for(int i=index;i<candidates.length;i++){
        numList.add(candidates[i]);
        combinationSum(candidates,target-candidates[i],i,numList,resultList);
        numList.remove(numList.size()-1);
    }
}

全排列

问题描述

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

问题分析

排列与组合类似,只是重复元素可以按照不同顺序成为不同的排列,我们不再是按顺序的取,而是定义一个used数组判断给定数组的元素是否被使用。当我们的排列结果中的元素与给定数组个数相同时,即得到一个排列,添加到结果数组中。

代码实现

java 复制代码
public List<List<Integer>> permute(int[] nums) {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> ans = new LinkedList<>();
    boolean[] used = new boolean[nums.length];
    permute(res,ans,used,nums);
    return res;
}
public void permute(List<List<Integer>> res,LinkedList<Integer> ans,boolean[] used,int[] nums){
    if(ans.size()==nums.length){
        res.add(new ArrayList<>(ans));
        return;
    }
    for(int i=0;i<nums.length;i++){
        if(used[i]){
            continue;
        }
        used[i] = true;
        ans.add(nums[i]);
        permute(res,ans,used,nums);
        ans.removeLast();
        used[i] = false;
    }
}
相关推荐
熬夜学编程的小王11 分钟前
C++类与对象深度解析(一):从抽象到实践的全面入门指南
c++·git·算法
CV工程师小林13 分钟前
【算法】DFS 系列之 穷举/暴搜/深搜/回溯/剪枝(下篇)
数据结构·c++·算法·leetcode·深度优先·剪枝
Dylanioucn17 分钟前
【分布式微服务云原生】掌握 Redis Cluster架构解析、动态扩展原理以及哈希槽分片算法
算法·云原生·架构
繁依Fanyi25 分钟前
旅游心动盲盒:开启个性化旅行新体验
java·服务器·python·算法·eclipse·tomcat·旅游
罔闻_spider35 分钟前
爬虫prc技术----小红书爬取解决xs
爬虫·python·算法·机器学习·自然语言处理·中文分词
Themberfue1 小时前
基础算法之双指针--Java实现(下)--LeetCode题解:有效三角形的个数-查找总价格为目标值的两个商品-三数之和-四数之和
java·开发语言·学习·算法·leetcode·双指针
陈序缘2 小时前
LeetCode讲解篇之322. 零钱兑换
算法·leetcode·职场和发展
-$_$-2 小时前
【LeetCode HOT 100】详细题解之二叉树篇
数据结构·算法·leetcode
大白飞飞2 小时前
力扣203.移除链表元素
算法·leetcode·链表
学无止境\n2 小时前
[C语言]指针和数组
c语言·数据结构·算法