-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
54 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
n,m = gets.split(" ").map{|el| el.to_i } | ||
c = gets.split(" ").map{|el| el.to_i } | ||
|
||
# coin change forumula | ||
# ways = ways to n with m-1 coins + ways to n - (c-1) with m coins | ||
|
||
def ways(n, m, c, memo = {}) | ||
return 1 if n == 0 | ||
return 0 if n < 1 || m == 0 | ||
memo[n] ||= {} | ||
return memo[n][m] if memo[n][m] | ||
memo[n][m] = ways(n, m-1, c, memo) + ways(n - c[m-1], m, c, memo) | ||
return memo[n][m] | ||
end | ||
|
||
puts ways(n, m, c) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
import Foundation | ||
let line = readLine()!.components(separatedBy: " ").map{ Int($0)! } | ||
let n = line[0] | ||
let m = line[1] | ||
let c = readLine()!.components(separatedBy: " ").map{ Int($0)! } | ||
|
||
func ways(_ n: Int, _ m: Int, _ c: [Int], _ w: inout [Int:[Int:Int]]) -> Int { | ||
if n == 0 { return 1 } | ||
if n < 1 || m == 0 { return 0 } | ||
if w[n] != nil && w[n]![m] != nil { return w[n]![m]! } | ||
w[n] = w[n] ?? [Int:Int]() | ||
w[n]![m] = ways(n, m-1, c, &w) + ways(n-c[m-1], m, c, &w) | ||
return w[n]![m]! | ||
} | ||
|
||
var w = [Int:[Int:Int]]() | ||
print("\(String(describing: ways(n,m,c,&w)))") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters