给你一个整数数组 nums
,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
方法一:递归法
从空集开始,一个个把数据往已有结果里面加,直到所有的数据加入完毕。
public List<List<Integer>> subsets(int[] nums ) {
List<List<Integer>> res = new ArrayList<>();
res.add(new ArrayList<>());//增加空集
for(int num:nums) {
List<List<Integer>> newSubsets = new ArrayList<>();
for (List<Integer> subset:res) {
List<Integer> newSubset = new ArrayList<>(subset);
newSubset.add(num);
newSubsets.add(newSubset);
}
res.addAll(newSubsets);
}
return res;
}
方法二:回溯法
//回溯法
List<List<Integer>> result = new ArrayList<>();
int n;
public List<List<Integer>> subsets1(int[] nums ) {
n = nums.length;
for (int k = 0;k <= n;k++) {
backtrack(0,k,new ArrayList<>(),nums);
}
return result;
}
public void backtrack(int start,int k,ArrayList<Integer> cur,int[] nums){
if(k == 0){
result.add(new ArrayList<>());
return;
}
for (int i = start;i<n;i++) {
cur.add(nums[i]);
backtrack(i+1,k-1,cur,nums);
cur.remove(cur.size()-1);
}
}
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn )。
示例 1:
输入:x = 2.00000, n = 10
输出:1024.00000
示例 2:
输入:x = 2.10000, n = 3
输出:9.26100
示例 3:
输入:x = 2.00000, n = -2
输出:0.25000
解释:2-2 = 1/22 = 1/4 = 0.25
方法一:递归
class Solution {
public double myPow(double x, int n) {
long N = n;
return N >= 0 ? quickMul(x, N) : 1.0 / quickMul(x, -N);
}
public double quickMul(double x, long N) {
if (N == 0) {
return 1.0;
}
double y = quickMul(x, N / 2);
return N % 2 == 0 ? y * y : y * y * x;
}
}
方法二:迭代
class Solution {
public double myPow(double x, int n) {
long N = n;
return N >= 0 ? quickMul(x, N) : 1.0 / quickMul(x, -N);
}
public double quickMul(double x, long N) {
double ans = 1.0;
// 贡献的初始值为 x
double x_contribute = x;
// 在对 N 进行二进制拆分的同时计算答案
while (N > 0) {
if (N % 2 == 1) {
// 如果 N 二进制表示的最低位为 1,那么需要计入贡献
ans *= x_contribute;
}
// 将贡献不断地平方
x_contribute *= x_contribute;
// 舍弃 N 二进制表示的最低位,这样我们每次只要判断最低位即可
N /= 2;
}
return ans;
}
}