leetCode 78.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],
  []
]

思路:这题和上题的组合差点儿相同。仅仅是k的数字是变动的。从0-n。

所以对照上一题,也就是对K加个循环。

代码例如以下:

public class Solution {
    boolean[] f;
    List<List<Integer>> list;
    public List<List<Integer>> subsets(int[] nums) {
        list = new ArrayList<List<Integer>>();
        
        if(nums.length == 0){//必须是有效k值
            return list;
        }
        f = new boolean[nums.length];

        for(int i = 0; i <= nums.length;i++){
        	count(nums,"",i,0);//调用函数
        }
        
        return list;
    }
    /**
     * 实现对k个数字的排练组合
     * @param a 数组
     * @param s 排练组合得到的结果
     * @param nn 排练组合的数字个数
     */
    private void count(int[] a,String s,int nn,int j){
        if(nn == 0){//处理结果
            String[] sa = s.split(",");//切割数组
            List<Integer> al = new ArrayList<Integer>();
            for(int i = 0;i < sa.length; i++){
                if(sa[i].length() > 0)//仅仅有当不为空的时候才加入
                	al.add(Integer.parseInt(sa[i]));//加入
            }
            Collections.sort(al);//排序,非降序
            list.add(al);
            return;
        }
        //遍历,从i=j開始。仅仅要i开头的与i大的值
        for(int i = j; i < a.length; i++){
            if(!f[i]){
                f[i] = true;
                count(a,s + "," + a[i],nn-1,i+1);//调用下一个为false的数字
                f[i] = false;
            }
        }
    }
}



原文地址:https://www.cnblogs.com/gccbuaa/p/6826181.html