我无法在2D数组中存储数组的子集。
在递归部分需要帮助。
public static int[][] subsets(int input[]) {
int index=0;
return help(input , index);
}
private static int[][] help(int []input, int index){
int n= input.length;
if(index >= input.length){
int ans[][]= new int [0][0];
return ans;
}
int samllAns[][] = help(input, index+1);
int ans[][] = new int[(n*n)][];
/* unable to get this part*/
return ans;
}
答案 0 :(得分:0)
这是我的答案。有效运作。它将以2D数组的形式返回输出。
public static void PrintSubsets(int[] input, boolean[] ifPrint, int
start, int remain){
if(remain==0)
{
for(int i=0; i<ifPrint.length;i++)
{
if(ifPrint[i])
System.out.print(input[i]+" ");
}
System.out.print("\n");
}
else if(start+remain>input.length)
return;
else
{
for(int i = start; i<input.length; i++)
{
if(!ifPrint[i])
{
ifPrint[i]=true;
PrintSubsets(input, ifPrint, i+1, remain-1);
ifPrint[i]=false;
}
}
}
` }
public static int[][] subsets(int input[]) {
return subsets(input,0);
}
public static int[][] subsets(int input[], int StartIndex) {
if(StartIndex==input.length)
{
return new int[1][0];
}
int SmallAns1[][]=subsets(input,StartIndex+1);
int SmallAns2[][]=subsets(input,StartIndex+1);
int ans[][]=new int[SmallAns1.length+SmallAns2.length][];
int l=0;
for(int i=0;i<SmallAns1.length;i++)
{
ans[l]=new int[SmallAns1[i].length + 1];
ans[l][0] = input[StartIndex];
for(int j=1;j<=SmallAns1[i].length;j++)
{
ans[l][j]=SmallAns1[i][j - 1];
}
l++;
}
for(int i=0;i<SmallAns2.length;i++)
{
ans[l]=new int[SmallAns2[i].length];
for(int j=0;j<SmallAns2[i].length;j++)
{
ans[l][j]=SmallAns2[i][j];
}
l++;
}
return ans;
}
答案 1 :(得分:0)
public class solution {
public static int[][] subsets(int input[],int index){
if(index>=input.length){
int[][] myAns = new int[1][0];
return myAns;
}
int[][] smallAns = subsets(input,index+1);
int[][] ans = new int[2*smallAns.length][];
int k =0;
int len = smallAns.length;
for(int i=0;i<len;i++){
ans[k] = new int[smallAns[i].length];
for(int j=0;j<smallAns[i].length;j++){
ans[k][j] = smallAns[i][j];
}
k++;
}
for(int i=0;i<len;i++){
ans[k] = new int[smallAns[i].length+1];
ans[k][0] = input[index];
for(int j=1;j<=smallAns[i].length;j++){
ans[k][j] = smallAns[i][j-1];
}
k++;
}
return ans;
}
public static int[][] subsets(int input[])
{
return subsets(input,0);
}
}