类似 array1=[2,2,2,2],array2=[2,3,3],array3[3.5],变成array4=[[2,2,2,2],[2,3,3],[3,5]]
#include <stdio.h>
#include <stdlib.h>
int** combinationSum( int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes )
{
int** retval = malloc( 150*sizeof(int*) ); // 对于给定的输入,保证和为 target 的唯一组合数少于 150 个
*returnColumnSizes = malloc( 150*sizeof(int) );
*returnSize = 0;
int buf[30*200+1]; // 1<=candidates.length<=30, 1<=candidates[i]<=200, 1<=target<=500
int bufSize = 0;
int sum = 0;
while( 1 )
{
//for( int i=0; i!=bufSize; ++i )
// printf( "%d%c", candidates[buf[i]], " \n"[i+1==bufSize] );
if( sum == target )
{
(*returnColumnSizes)[*returnSize] = bufSize;
retval[*returnSize] = malloc( bufSize*sizeof(int) );
for( int i=0; i!=bufSize; ++i )
retval[*returnSize][i] = candidates[buf[i]];
++*returnSize;
}
if( sum < target )
{
int last = bufSize==0 ? 0 : buf[bufSize-1];
buf[bufSize++] = last;
sum += candidates[last];
}
else
{
for( ; bufSize!=0 && buf[bufSize-1]==candidatesSize-1; --bufSize )
sum -= candidates[candidatesSize-1];
if( bufSize == 0 )
break;
sum += -candidates[buf[bufSize-1]] + candidates[buf[bufSize-1]+1];
++buf[bufSize-1];
}
}
return retval;
}
int main( void )
{
int candidates[] = { 2,3,6,7 };
int candidatesSize = sizeof(candidates)/sizeof(*candidates);
int target = 7;
int returnSize;
int* returnColumnSizes;
int** retval = combinationSum( candidates, candidatesSize, target, &returnSize, &returnColumnSizes );
for( int i=0; i!=returnSize; ++i )
{
for( int j=0; j!=returnColumnSizes[i]; ++j )
printf( "%d%c", retval[i][j], ",\n"[j+1==returnColumnSizes[i]] );
}
}
0.0分
0 人评分
数列 (C++代码)浏览:707 |
C语言程序设计教程(第三版)课后习题8.4 (Java代码)浏览:788 |
C语言程序设计教程(第三版)课后习题10.1 (Java代码)浏览:1492 |
C语言程序设计教程(第三版)课后习题10.5 (C语言代码)浏览:566 |
回文数(一) (C语言代码)浏览:809 |
众数问题 (C语言代码)浏览:911 |
剪刀石头布 (C语言代码)浏览:1792 |
C语言程序设计教程(第三版)课后习题9.8 (C语言代码)浏览:646 |
C语言程序设计教程(第三版)课后习题8.9 (C语言代码)浏览:897 |
DNA (C语言代码)浏览:564 |