迭代法:
用二进制位表示各数选与不选
function subsets($nums) {
$len = count($nums);
$R = [];
foreach (range(0, (1 << $len) - 1) as $mask) {
$temp = [];
for ($i=0; $i<$len; $i++) {
if (($mask & (1 << $i)) !== 0) {
$temp[] = $nums[$i];
}
}
$R[] = $temp;
}
return $R;
}
递归回溯
class Solution {
/**
* @param Integer[] $nums
* @return Integer[][]
*/
function subsets($nums) {
$this->helper($rlt, $nums, 0, count($nums));
return $rlt;
}
private function helper(&$rlt, $nums, $cur, $len, &$temp=[]) {
if ($cur == $len) {
$rlt[] = $temp;
return;
}
$pos = count($temp);
// cur位的元素被选入子集中
$temp[$pos] = $nums[$cur];
$this->helper($rlt, $nums, $cur+1, $len, $temp);
// 状态回溯
unset($temp[$pos]);
// cur位元素不被选入
$this->helper($rlt, $nums, $cur+1, $len, $temp);
}
}