题目
题目链接:
https://www.nowcoder.com/practice/c333d551eb6243e0b4d92e37a06fbfc9
思路
递归实现:先升序排序;然后每个位置i为起点,i到最后的数,要么被选择,要么被放弃
递归实现;注意结果集,长度短的子集放前面
参考答案Java
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param S int整型一维数组
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> subsets (int[] S) {
Arrays.sort(S);
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
Map<Integer,ArrayList<ArrayList<Integer>>> help = new HashMap<>();
ans.add(new ArrayList<>());
dfs(S,0,new ArrayList<Integer>(),help);
//System.out.println(help);
for (int i = 1; i <=S.length ; i++) {
ArrayList<ArrayList<Integer>> arrayLists = help.get(i);
for (ArrayList<Integer> arrayList : arrayLists) {
// System.out.println(arrayList);
ans.add(arrayList);
}
}
return ans;
}
public void dfs(int[] arr,int index,ArrayList<Integer> path,Map<Integer,ArrayList<ArrayList<Integer>>> help ){
if(path.size()>0){
//ans.add(new ArrayList<>(path));
int mkey = path.size();
if(!help.containsKey(mkey))
help.put(mkey,new ArrayList<>());
help.get(mkey).add(new ArrayList<>(path));
}
for (int i = index; i <arr.length ; i++) {
path.add(arr[i]);
dfs(arr,i+1,path,help);
path.remove(path.size()-1); //恢复现场
}
}
}
参考答案Go
package main
import "sort"
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param S int整型一维数组
* @return int整型二维数组
*/
func subsets(S []int) [][]int {
//dfs
sort.Ints(S)
imap := map[int][][]int{}
imap[0] = make([][]int, 0)
path := []int{}
dfs(S, 0, path, imap)
ans := [][]int{}
ans = append(ans, []int{})
//fmt.Println(imap)
for i := 0; i <= len(S); i++ {
nexts := imap[i]
for _, next := range nexts {
ans = append(ans, next)
}
}
return ans
}
func dfs(arr []int, index int, path []int, imap map[int][][]int) {
//fmt.Println(path)
if len(path) > 0 {
mkey := len(path)
_, ok := imap[mkey]
if !ok {
imap[mkey] = [][]int{}
}
pathbak := make([]int, mkey)
for k := 0; k < mkey; k++ {
pathbak[k] = path[k]
}
imap[mkey] = append(imap[mkey], pathbak)
}
for i := index; i < len(arr); i++ {
path = append(path, arr[i])
dfs(arr, i+1, path, imap)
pathbak := path[:len(path)-1]
path = pathbak //恢复现场
}
}
参考答案PHP
<?php
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param S int整型一维数组
* @return int整型二维数组
*/
function subsets( $S )
{
sort($S);
$path = array();
$map = array();
dfs($S,0,$path,$map);
$ans = [0=>[]];
for($i=1;$i<=count($S);$i++){
$nexts = $map[$i];
foreach ($nexts as $next){
$ans[count($ans)] = $next;
}
}
return $ans;
}
function dfs($arr,$index,$path,&$map){
if(count($path) >0 ){
$mkey = count($path);
if(!isset($map[$mkey])){
$map[$mkey] =array();
}
$pathbak=array();
for($m=0;$m<$mkey;$m++){
$pathbak[$m] = $path[$m];
}
$cnt= count($map[$mkey]);
$map[$mkey][$cnt] = $pathbak;
}
for($i=$index;$i<count($arr);$i++){
array_push($path,$arr[$i]);
dfs($arr,$i+1,$path,$map);
array_pop($path); //恢复现场
}
}