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);
        }
    }
}

 

posted @ 2018-10-12 18:46  XIAOSHUA  阅读(165)  评论(0编辑  收藏  举报