首页 > 编程语言 >算法学习day29回溯part05-491、46、47

算法学习day29回溯part05-491、46、47

时间:2023-05-29 22:14:18浏览次数:45  
标签:used day29 nums 46 47 int static path public

package LeetCode.backtrackpart05;
import java.util.ArrayList;
import java.util.List;

/**
 * 491. 递增子序列
 * 给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。
 * 你可以按 任意顺序 返回答案。
 * 数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。
 * 示例:
 * 输入:nums = [4,6,7,7]
 * 输出:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
 * */

public class NonDecreasingSubsequences_491 {
    public static List<Integer> path = new ArrayList<>();
    public static List<List<Integer>> res = new ArrayList<>();
    public static void main(String[] args) {
        int [] nums = {4,6,7,7};
        res = findSubsequences(nums);
        System.out.println(res);
    }
    public static List<List<Integer>> findSubsequences(int [] nums){
        backtracking(nums,0);
        return res;
    }
    public static void backtracking(int [] nums,int startIndex){
        // 题目要求:子序列中至少有两个元素
        if (path.size() > 1){
            res.add(new ArrayList<>(path));
        }
        int [] used = new int[201];
        for (int i = startIndex; i < nums.length; i++) {
            if (!path.isEmpty() && nums[i] < path.get(path.size() - 1) || (used[nums[i] + 100] == 1)) {
                continue;
            }
            used[nums[i] + 100] = 1;
            path.add(nums[i]);
            backtracking(nums, i + 1);
            path.remove(path.size() - 1);
        }
    }
}
package LeetCode.backtrackpart05;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 46. 全排列
 * 给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
 * 示例:
 * 输入:nums = [1,2,3]
 * 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
 * */

public class Permutations_46 {
    public static List<List<Integer>> result = new ArrayList<>();// 存放符合条件结果的集合
    public static LinkedList<Integer> path = new LinkedList<>();// 用来存放符合条件结果
    public static boolean[] used;
    public static void main(String[] args) {

        int [] nums = {1,2,3};
        result = permute(nums);
        System.out.println(result);
    }
    public static List<List<Integer>> permute(int[] nums) {
        if (nums.length == 0){
            return result;
        }
        used = new boolean[nums.length];
        permuteHelper(nums);
        return result;
    }


    public static void permuteHelper(int[] nums){
        if (path.size() == nums.length){
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++){
            if (used[i]){
                continue;
            }
            used[i] = true;
            path.add(nums[i]);
            permuteHelper(nums);
            path.removeLast();
            used[i] = false;
        }
    }

}
package LeetCode.backtrackpart05;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 47. 全排列 II
 * 给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
 * 示例:
 * 输入:nums = [1,2,3]
 * 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
 * */

public class PermutationsII_47 {
    public static List<List<Integer>> result = new ArrayList<>();// 存放符合条件结果的集合
    public static LinkedList<Integer> path = new LinkedList<>();// 用来存放符合条件结果
    public static void main(String[] args) {
        int [] nums = {1,2,3};
        result = permuteUnique(nums);
        System.out.println(result);
    }
    public static List<List<Integer>> permuteUnique(int[] nums) {
        boolean[] used = new boolean[nums.length];
        Arrays.fill(used, false);
        Arrays.sort(nums);
        backtracking(nums, used);
        return result;
    }

    public static void backtracking(int [] nums,boolean [] used){
        if (path.size() == nums.length) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            // used[i - 1] == true,说明同⼀树⽀nums[i - 1]使⽤过
            // used[i - 1] == false,说明同⼀树层nums[i - 1]使⽤过
            // 如果同⼀树层nums[i - 1]使⽤过则直接跳过
            if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
                continue;
            }
            //如果同⼀树⽀nums[i]没使⽤过开始处理
            if (used[i] == false) {
                used[i] = true;//标记同⼀树⽀nums[i]使⽤过,防止同一树枝重复使用
                path.add(nums[i]);
                backtracking(nums, used);
                path.remove(path.size() - 1);//回溯,说明同⼀树层nums[i]使⽤过,防止下一树层重复
                used[i] = false;//回溯
            }
        }

    }

}

 

标签:used,day29,nums,46,47,int,static,path,public
From: https://www.cnblogs.com/lipinbigdata/p/17441809.html

相关文章

  • poj 2346(DP)
    题意:n位数,满足前n/2个数字之和同后n/2个数字之和相同的数一共有多少个?解题思路:dp[i][j]表示前i个数的和为j时,有多少个;递推关系:dp[i][j]+=dp[i-1][k],k表示前i-1个数的和,由于每一位只能是0-9,所以有限制条件:9>=j - k>=0由于对称性,只需要枚举到n/2即可,剩下的就是简单的乘法......
  • Q460MD钢板简介、Q460MD交货状态、Q460MD高强钢
    一、Q460MD钢板简介:Q460MD钢属于低合金高强度结构钢,具有较高的强度、良好的抗疲劳性能、低温韧性以及冷成型和焊接性能。Q460MD/E钢板牌号表示:“Q”:表示钢板屈服强度“屈”的拼音首字母;“460”:表示钢板的屈服强度为460MPa;“M”:表示钢板以TMCP轧制交货。“D”:表示钢板质量等级;“D”......
  • sockjs.js:1603 GET http://localhost/sockjs-node/info?t=1685340190468 net::ER
    vue项目报错不影响运行,但控制台看到这报错,属实不舒服 解决方法:进入\node_modules\sockjs-client\dist\sockjs.js注释1603行   刷新页面,没报错了 ......
  • LeetCode 周赛 347(2023/05/28)二维空间上的 LIS 最长递增子序列问题
    本文已收录到AndroidFamily,技术和职场问题,请关注公众号[彭旭锐]提问。往期回顾:LeetCode单周赛第346场·仅68人AK的最短路问题周赛347概览T1. 移除字符串中的尾随零(Easy)标签:模拟、字符串T2.对角线上不同值的数量差(Easy)标签:前后缀分解T3.使所有字符......
  • 746. Min Cost Climbing Stairs刷题笔记
    题目描述出bug的时候输出打印dp就行classSolution:defminCostClimbingStairs(self,cost:List[int])->int:n=len(cost)+1ifn<=3:returnmin(cost[0],cost[1])dp=[0]*ncost.append(0)foriinrange(2......
  • 1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
    将数组排序之后,进行差分,然后选择各自最大的能够元素相乘,就能得到最大的蛋糕块了。注意按照题目要求,最终结果要取余数classSolution:defmaxArea(self,h:int,w:int,horizontalCuts:List[int],verticalCuts:List[int])->int:horizontalCuts.sort()......
  • 647. Palindromic Substrings刷题笔记
    用动态规划可以做,应该可以优化为只有两个表,而且不用每次res都加classSolution:defcountSubstrings(self,s:str)->int:n=len(s)dp=[[0]*nfor_inrange(n)]res=0foriinrange(n-1,-1,-1):forji......
  • P5446 [THUPC2018]绿绿和串串 题解
    Description给定一个串\(S\),要求串\(S\)是串\(R\)经过多次翻转后的前缀。问有多少种初始长度的串\(R\)。串\(R\)翻转的定义是将前\(|R|-1\)个字符倒序排列后,插入到串的最后。如\(\mathrm{aaa}\)翻转后得到\(\mathrm{abcdcba}\)。Solution我们先设以\(i\)为......
  • error CS0246: The type or namespace name ‘NetworkManager‘ could not be found
    项目场景:之前用Unity5.x开发的项目,要升级到Unity2019问题描述:因为项目中用到了老版的Network导致升级后报错errorCS0246:Thetypeornamespacename'NetworkManager'couldnotbefound(areyoumissingausingdirectiveoranassemblyreference?)<hrstyle="border:s......
  • AtCoder Regular Contest 146 D >=<
    洛谷传送门AtCoder传送门考虑直接增量构造。把条件拆成形如\(a_u\gex\)时\(a_v\gets\max(a_v,y)\),连边,跑类似一个spfa的东西,就行了。这样一定能构造出一组和最小的解。code//Problem:D->=<//Contest:AtCoder-AtCoderRegularContest146//URL:http......