Knapsack 01 Dynamic Programming (Rust)
Solve the 0-1 knapsack problem in Rust using dynamic programming with a rolling vector for space optimization.
Code
fn knapsack01(weights: &[i32], values: &[i32], capacity: i32) -> i32 {
let n = weights.len();
let mut dp = vec![0i32; (capacity + 1) as usize];
for i in 0..n {
let mut next = vec![0i32; (capacity + 1) as usize];
for w in 0..=capacity {
next[w as usize] = dp[w as usize];
if w >= weights[i] && dp[(w - weights[i]) as usize] + values[i] > next[w as usize] {
next[w as usize] = dp[(w - weights[i]) as usize] + values[i];
}
}
dp = next;
}
dp[capacity as usize]
}How it works
Knapsack 01 Dynamic Programming (Rust) keeps everything in the function knapsack01.
The loop for i in 0..n is the only repeated construct.
Applying it
The primary signature is fn knapsack01(weights: &[i32], values: &[i32], capacity: i32) -> i32
knapsack01 is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
next[w as usize] = dp[(w - weights[i]) as usize] + values[i];
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. The file defines `knapsack01` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.