Printing all possible subsets of a list

后端 未结 7 1377
半阙折子戏
半阙折子戏 2020-12-28 11:18

I have a List of elements (1, 2, 3), and I need to get the superset (powerset) of that list (without repeating elements). So basically I need to create a List of Lists that

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-28 12:08

    In the given solution we iterate over every index and include current and all further elements.

    class Solution {
            public List> subsets(int[] nums) {
                List> ans = new ArrayList<>();
                if(nums == null || nums.length ==0){
                    return ans;
                }
                Arrays.sort(nums);
                List subset = new ArrayList<>();
                allSubset(nums, ans , subset , 0);
                return ans;
            }
            private void allSubset(int[] nums,List> ans ,List subset , int idx){
                ans.add(new ArrayList<>(subset));
                for(int i = idx; i < nums.length; i++){
                    subset.add(nums[i]);
                    allSubset(nums, ans , subset , i+1);
                    subset.remove(subset.size() - 1);
                }
            }
            
    }
    

提交回复
热议问题