Leetcode 题目解析之 Subsets
        【摘要】 Leetcode 题目解析之 Subsets
    
    
    
    Given a set of distinct integers, nums, 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 nums = 1,2,3, a solution is:
[
3,
1,
2,
1,2,3,
1,3,
2,3,
1,2,
[]
]
    int target;// 次数
    Integer[] stack;// 存储每次排列
    List<List<Integer>> rt;// 存储结果
    public void search(int p, int[] nums) {
        // 若长度为k,则stack是其中一个结果,保存结果
        if (p == target) {
            rt.add(new ArrayList<Integer>(Arrays.asList(stack)));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (p > 0 && nums[i] <= stack[p - 1]) {
                continue;
            }
            stack[p] = nums[i];
            search(p + 1, nums);
        }
    }
    public List<List<Integer>> subsets(int[] nums) {
        Arrays.sort(nums);
        rt = new ArrayList<List<Integer>>();
        // 分别做0~num.length长度的组合
        for (int i = 0; i <= nums.length; i++) {
            target = i;
            stack = new Integer[i];
            search(0, nums);
        }
        return rt;
    }
 
            【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
                cloudbbs@huaweicloud.com
                
            
        
        
        
        
        - 点赞
 - 收藏
 - 关注作者
 
            
           
评论(0)