leetcode面试题 08.04. 幂集(递归)
生活随笔
收集整理的這篇文章主要介紹了
leetcode面试题 08.04. 幂集(递归)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
冪集。編寫一種方法,返回某集合的所有子集。集合中不包含重復的元素。
說明:解集不能包含重復的子集。
示例:
輸入: nums = [1,2,3]
輸出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
代碼
class Solution {List<List<Integer>> ress=new ArrayList<>();public List<List<Integer>> subsets(int[] nums) {sub(nums,0); return ress;}public void sub(int[] nums,int loc) {List<List<Integer>> ss=new ArrayList<>();if(loc==nums.length)//遞歸邊界{ress.add(new ArrayList<>());return ;}sub(nums, loc+1);List<List<Integer>> next=new ArrayList<>(ress);for(List<Integer> l:ress)//將后面的子集和當前的連接{ArrayList<Integer> na=new ArrayList<>(l);na.add(nums[loc]);next.add(new ArrayList<>(na));}ress=next;//刷新子集結果} }總結
以上是生活随笔為你收集整理的leetcode面试题 08.04. 幂集(递归)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到自己卖桃子是什么意思
- 下一篇: leetcode78. 子集(回溯)