首页 > 代码库 > [leetcode] Subsets
[leetcode] Subsets
Given a set of distinct integers, S, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If S = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], []]
https://oj.leetcode.com/problems/subsets/
思路:递归构造,每一层递归都选择填或者不填s[cur]的操作。
import java.util.ArrayList;import java.util.Arrays;public class Solution { public ArrayList<ArrayList<Integer>> subsets(int[] S) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> tmp = new ArrayList<Integer>(); Arrays.sort(S); subsetsHelper(res, tmp, S, 0); return res; } private void subsetsHelper(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp, int[] s, int cur) { if (cur == s.length) { res.add(new ArrayList<Integer>(tmp)); return; } // not fill subsetsHelper(res, tmp, s, cur + 1); // fill tmp.add(s[cur]); subsetsHelper(res, tmp, s, cur + 1); tmp.remove(tmp.size() - 1); } public static void main(String[] args) { System.out.println(new Solution().subsets(new int[] { 4, 1, 0 })); }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。