zoukankan      html  css  js  c++  java
  • 11/5 <backtracking> 伪BFS+回溯

    78. Subsets

    While iterating through all numbers, for each new number, we can either pick it or not pick it
    1, if pick, just add current number to every existing subset.
    2, if not pick, just leave all existing subsets as they are.
    We just combine both into our result.

    For example, {1,2,3} intially we have an emtpy set as result [ [ ] ]
    Considering 1, if not use it, still [ ], if use 1, add it to [ ], so we have [1] now
    Combine them, now we have [ [ ], [1] ] as all possible subset

    Next considering 2, if not use it, we still have [ [ ], [1] ], if use 2, just add 2 to each previous subset, we have [2], [1,2]
    Combine them, now we have [ [ ], [1], [2], [1,2] ]

    Next considering 3, if not use it, we still have [ [ ], [1], [2], [1,2] ], if use 3, just add 3 to each previous subset, we have [ [3], [1,3], [2,3], [1,2,3] ]
    Combine them, now we have [ [ ], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3] ]

    class Solution {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> result = new ArrayList<>();
            result.add(new ArrayList<>());
            for(int n : nums){
                int size = result.size();
                for(int i = 0; i < size; i++){
                    List<Integer> subset = new ArrayList<>(result.get(i));
                    subset.add(n);
                    result.add(subset);
                }
            }
            return result;
        }
    }

    90. Subsets II

    我们用 lastAdded 来记录上一个处理的数字,然后判定当前的数字和上面的是否相同,若不同,则循环还是从0到当前子集的个数,若相同,则新子集个数减去之前循环时子集的个数当做起点来循环

    class Solution {
        public List<List<Integer>> subsetsWithDup(int[] nums) {
            Arrays.sort(nums);
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            result.add(new ArrayList<Integer>());
            int lastAdded = 0;
            for(int i = 0; i < nums.length; i++){
                if(i == 0 || nums[i] != nums[i-1]) lastAdded = 0;
                int size = result.size();
                for(int j = lastAdded; j < size; j++){
                    List<Integer> cur = new ArrayList<Integer>(result.get(j));
                    cur.add(nums[i]);
                    result.add(cur);
                }
                lastAdded = size;
            }
            return result;
        }
    }
  • 相关阅读:
    站点防攻击之禁止国外ip
    docker 安装rabbitMQ
    【转】浅析支付系统的整体架构
    【转】MQ详解及四大MQ比较
    SQL server 中的dbo、guest
    网站加载速度的优化(1):优化前端页面
    【转】Apache ab压力测试
    Asp.Net Core 部署发布后EFCore数据库断连和Google浏览器无法存储Cookie
    C# 使用nuget.exe发布类库及更新类库
    .net core 读取Excal文件数据及注意事项
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11800033.html
Copyright © 2011-2022 走看看