- public static void subsets(int n, int k) {
- subsets(n, k, "");
- }
- public static void subsets(int n, int k, String s) {
- if (k == 0)
- System.out.println(s);
- else if (n > 0) {
- subsets(n-1, k, s);
- subsets(n-1, k-1, n+s);
- }
- }
Approximate grading key for סעיף ג is as follows:
- A +2 : correct base case condition (line 6)
- B +1 : correct base case action (line 7)
- C +3 : correct reduction case condition (line 8,
n >= kis also OK, or justelsewithn > kcondition for line 9 only) - D +6 : correct separation into two recursive calls (lines 9-10)
- E +2 : correct use of String concatenation (
n+sin line 10)
- F 0..-3 : syntax errors
- G 0..-3 : inelegant code
- H -2 : concatenation of string accumulator in both/neither recursive calls
- I 0..-3 : excessive parameters with no real use
- J 0..-3 : wrong use of return/prints (i.e., misunderstanding the
void)
Another nice solution:
- public static void subsets(int n, int k, String s) {
- if (k == 0)
- System.out.println(s);
- else
- for (int i = k; i <= n; ++i)
- subsets(i-1, k-1, i+s);
- }
There are, of course, variants of either approach with extra parameters.
Another interesting alternative:
- public static void subsets(int n, int k, String s) {
- if (k == 0)
- System.out.println(s);
- else if (n == k) {
- for (int i = 1; i <= n; ++i)
- s = s + i;
- System.out.println(s);
- }
- else {
- subsets(n-1, k-1, n+s);
- subsets(n-1, k, s);
- }
- }