LeetCode subsets

Posted 学习、实践、总结

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode subsets相关的知识,希望对你有一定的参考价值。

迭代算法:

import java.util.LinkedList;
import java.util.List;

class Solution {

    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        res.add(new LinkedList<>());
        for (int i = nums.length; i > 0; i--) {
            int size = res.size();
            for (int k = 0; k < size; k++) {
                List<Integer> path2 = new LinkedList<>(res.get(k));
                path2.add(nums[i - 1]);
                res.add(path2);
            }
        }
        return res;
    }
}

递归算法:

import java.util.LinkedList;
import java.util.List;

class Solution {

    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> routes = new LinkedList<>();
        buildRoutes(routes, new LinkedList<>(), nums.length, nums);
        return routes;
    }

    private void buildRoutes(List<List<Integer>> routes, List<Integer> link, int count, int[] nums) {
        if (count > 0) {
            buildRoutes(routes, link, count - 1, nums);
            List<Integer> link2 = new LinkedList<>(link);
            link2.add(nums[count - 1]);
            buildRoutes(routes, link2, count - 1, nums);
        } else {
            routes.add(link);
        }
    }
}

 

以上是关于LeetCode subsets的主要内容,如果未能解决你的问题,请参考以下文章

Subsets II -- LeetCode

Leetcode 78. Subsets (backtracking) 90 subset

Leetcode 78. Subsets

#Leetcode# 90. Subsets II

LeetCode 90:Subsets II

LeetCode OJ 078Subsets