Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b8f70b5

Browse files
zhangzz2015gitbook-bot
authored andcommitted
GitBook: [greyireland#106] No subject
1 parent ae247d9 commit b8f70b5

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

‎basic_algorithm/dp.md‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -756,6 +756,66 @@ func min(a,b int)int{
756756

757757
> dp\[i-a\[j]] 决策 a\[j]是否参与
758758
759+
Coin Change 2
760+
761+
```cpp
762+
// Some code
763+
class Solution {
764+
public:
765+
int change(int amount, vector<int>& coins) {
766+
767+
// Time O(n*m) Space O(n*m) Cost: 15min.
768+
/// dp[i][j] chose from 0 to i coins and get target amount j. combination
769+
// dp[i][j] dp[i][j] = dp[i-1][j] + loop k from 0 to max num coins[i]. dp[i-1][j-coins[i]*k]
770+
// dp[i][j] dp[i][j] = dp[i-1][j] + dp[i][j - coins[i]] ;
771+
// we can improve it further to optimize memory to O(n)
772+
773+
vector<int> dp(amount+1, 0);
774+
dp[0] =1;
775+
for(int i=0; i<coins.size(); i++)
776+
{
777+
778+
for(int j=coins[i]; j <=amount; j++)
779+
{
780+
dp[j] +=dp[j-coins[i]];
781+
}
782+
}
783+
return dp[amount];
784+
}
785+
786+
int method1(int amount, vector<int>& coins)
787+
{
788+
vector<vector<int>> dp(coins.size()+1, vector<int>(amount+1, 0));
789+
790+
for(int i=0; i<=coins.size(); i++)
791+
{
792+
for(int j=0; j<=amount; j++)
793+
{
794+
if(j==0)
795+
dp[i][j] = 1;
796+
else if(i==0)
797+
dp[i][j] = 0;
798+
else
799+
{
800+
int k=0;
801+
/* while(j >=coins[i-1]*k)
802+
{
803+
dp[i][j] +=dp[i-1][j-coins[i-1]*k];
804+
k++;
805+
} */
806+
if(j-coins[i-1]>=0)
807+
dp[i][j] = dp[i-1][j] + dp[i][j-coins[i-1]];
808+
else
809+
dp[i][j] = dp[i-1][j] ;
810+
}
811+
}
812+
}
813+
814+
return dp[coins.size()][amount];
815+
}
816+
};
817+
```
818+
759819
### [backpack](https://www.lintcode.com/problem/backpack/description)
760820
761821
> 在 n 个物品中挑选若干物品装入背包,最多能装多满?假设背包的大小为 m,每个物品的大小为 A\[i]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /