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;
        }
    }
  • 相关阅读:
    JavaScript怎么让字符串和JSON相互转化
    golang怎么使用redis,最基础的有效的方法
    SmartGit过期后破解方法
    Mac下安装ElasticSearch
    浏览器滚动条拉底部的方法
    git 管理
    MAC远程连接服务器,不需要输入密码的配置方式
    centos6.5下使用yum完美搭建LNMP环境(php5.6) 无脑安装
    【笔记】LAMP 环境无脑安装配置 Centos 6.3
    vs2008不能创建C#项目的解决方法
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11800033.html
Copyright © 2011-2022 走看看