这个题也是不停的往里写数,没有重复非常容易解决。
public ArrayList<ArrayList<Integer>> subsets(int[] S) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
result.add(new ArrayList<Integer>());
Arrays.sort(S);
for (int i = 0; i < S.length; i++){
int size = result.size();
for (int j = 0; j < size; j++){
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.addAll(result.get(j));
temp.add(S[i]);
result.add(temp);
}
}
return result;
}
Leetcode changed the return type as <List<List<Integer>>. The updated solution is as follows:
public List<List<Integer>> subsets(int[] S) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
result.add(new ArrayList<Integer>());
Arrays.sort(S);
for (int i=0; i<S.length; i++) {
List<List<Integer>> newResult = new ArrayList<List<Integer>>();
newResult.addAll(result);
for (List<Integer> sub : newResult){
List<Integer> temp = new ArrayList<Integer>();
temp.addAll(sub);
temp.add(S[i]);
result.add(temp);
}
}
return result;
}
No comments:
Post a Comment