大牙苏:网络,网络编程,操作系统,数据库,数据结构和算法,至少一个拿得出手讲的透彻的项目,基本大数据处理等
0 点赞 评论 收藏
分享
CedricCode:献丑了。。不知道对不对,dp问题,dp[i][j]表示0-i个袋子装j个球的放法数
public class BallInPackage {
public int ballInPackage(int numsOfBags, int numsOfBalls)
{
int[][] dp = new int[numsOfBags][numsOfBalls + 1];
//initialization
for(int i = 0; i < numsOfBags; i++)
dp[i][0] = 1;
for(int i = 1; i <= numsOfBalls; i++)
dp[0][i] = 1;
//calculate the dp matrix
for(int i = 1; i < numsOfBags; i++) {
for(int j = 1; j <= numsOfBalls; j++) {
int nums = 0;
for(int k = 0; k <= j; k++)
nums += dp[i-1][k];
dp[i][j] = nums;
}
}
return dp[numsOfBags-1][numsOfBalls];
}
public int ballInPackage_Advanced(int numsOfBags, int numsOfBalls)
{
int[][] dp = new int[numsOfBags][numsOfBalls + 1];
//initialization
for(int i = 0; i < numsOfBags; i++)
dp[i][0] = 1;
dp[0][2] = 1; dp[0][3] = 1;
//calculate the dp matrix
for(int i = 1; i < numsOfBags; i++) {
for(int j = 1; j <= numsOfBalls; j++) {
if(j < 2)
dp[i][j] += dp[i-1][j];
else if(j == 2)
dp[i][j] += dp[i-1][j] + dp[i-1][j-2];
else if(j >= 3)
dp[i][j] += dp[i-1][j] + dp[i-1][j-2] + dp[i-1][j-3];
else
dp[i][j] = 0;
}
}
return dp[numsOfBags-1][numsOfBalls];
}
public static void main(String[] args) {
BallInPackage b = new BallInPackage();
System.out.println(b.ballInPackage(12, 20));
System.out.println(b.ballInPackage_Advanced(12, 20));
}
}

0 点赞 评论 收藏
分享

0 点赞 评论 收藏
分享
ncncnc:struct ListNode{
int val;
struct ListNode *next;
};
struct ListNode* reverse(struct ListNode* head)
{
struct ListNode* new_head = NULL, *tmpNode;
while(head)
{
tmpNode = head->next;
head->next = new_head;
new_head = head;
head = tmpNode;
}
return new_head;
}
0 点赞 评论 收藏
分享
zxx178239:b没有分配内存,而且b本身也没初始化为NULL,自然无法返回NULL,也无法拷贝成功。

0 点赞 评论 收藏
分享
0 点赞 评论 收藏
分享
0 点赞 评论 收藏
分享
创作者周榜
更多
关注他的用户也关注了: