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], [] ]
找子集 要求,不递减排列
代码:
package leetcode;
import java.util.*;
public class Subsets {
public static List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
// res.add(new ArrayList<Integer>());
if (nums == null || nums.length < 1) { // 提前写好测试用例
res.add(new ArrayList<Integer>());
return res;
}
Arrays.sort(nums);
List<Integer> inres = new ArrayList<>();
inres.add(nums[0]);
res.add(inres);
for (int j = 1;j<nums.length;j++) {
int size = res.size();
for (int i = 0; i < size; i++) {
List<Integer> inres1 = new ArrayList<>(res.get(i));
// System.out.println(inres1);
inres1.add(nums[j]);
// System.out.println(inres1);
res.add(inres1);
//System.out.println(res);
}
List<Integer> inres2 = new ArrayList<>();
inres2.add(nums[j]);
// System.out.println(inres2);
res.add(inres2);
// System.out.println(res);
}
res.add(new ArrayList<Integer>());
return res;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] array = { 1, 2, 3, 5 };
// for(int i=0;i<subsets(array).size();i++){
// System.out.println(subsets(array).get(i));
// }
Long long1 = System.currentTimeMillis();
System.out.println(long1 + "毫秒!"); //判断运行时间的长短
for (List<Integer> j : subsets(array))
System.out.println(j);
Long long2 = System.currentTimeMillis();
System.out.println(long2 + "毫秒!");
Long long3 = long2 - long1;
System.out.println("耗时" + long3 + "毫秒!");
// System.out.println(subsets(array));
}
}
心得:
1、找出解的形式:返回值
2、测试驱动开发->编写前先写出特殊情况怎么处理,比如nums[] = null,长度为1.。。。。
3、对一般情况进行分析:比如数字题目,先找到数学上的推算过程->递推过程,然后用程序来表达出来!!!!
4、这个题目是:先找出一个list,在以往的list的每个元素上都 增加新的元素。
5、debug时,设置好 断点、变量、或者使用System.out.println输出来看看;
6、编程->先写出来一个,在慢慢优化!写的多了,思路就有了~
7、List<List<Integer>>类的用法,掌握list的全部方法,,add,set,get,remove等等
态度决定行为,行为决定习惯,习惯决定性格,性格决定命运

浙公网安备 33010602011771号