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;
        }
    }
  • 相关阅读:
    Hexo+Github搭建个人博客手记
    如何在Github上部署Hexo个人博客
    测试计划与测试方案的区别
    软件测试流程
    Python笔记-List和Tuple类型
    键盘无响应-如何修复键盘注册表
    正向代理与反向代理-小故事
    解决git连接github超时问题
    如何防范短信接口被恶意调用(被刷)
    接口测试基础篇
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11800033.html
Copyright © 2011-2022 走看看